0

I have a string containing information in the following format:

Maltese Age: 2 Price: $500
https://images.google/image
Staffy Age: 1 Price: $500
https://images.google/image
Yorkie Age: 2 Price: $300
https://images.google/image

My goal, is to turn the above into something like this:

Dogs:
{
     "dog": "Pomeranian",
"info": {
    "url": "https://images.google.com/image",
    "age": 2,
    "price": 1000
}


And of course loop around back and fourth for all of the pets I have in the string.

3
  • are you already using any json library? Commented May 13, 2021 at 15:04
  • I'm using org.json, yeah Commented May 13, 2021 at 15:07
  • Use regexes to obtain the different groups and use your json library to turn the results into the JSON object you describe. Commented May 13, 2021 at 15:09

2 Answers 2

1

If you use regular expressions you can get the values like this:

JSONArray arr = new JSONArray();
Matcher m = Pattern.compile("([^ \\r\\n]*) Age: ?(\\d+) Price: ?\\$?(\\d+(?:\\.\\d*)?)\\r?\\n(http[^ \\r\\n]*)").matcher(str);
while (m.find()) {
    String dog = m.group(1);
    String age = m.group(2);
    String price = m.group(3);
    String url = m.group(4);

    // Add to a JSON object using your preferred JSON library
    // Example:
    JSONObject obj = new JSONObject();
    obj.put("dog",dog);

    JSONObject info = new JSONObject();
    info.put("age",age);
    info.put("price",price);
    info.put("url",url);

    obj.put("info",info);
    arr.put(obj);
}
Sign up to request clarification or add additional context in comments.

Comments

0

There are probably multiple ways to do it, but one way to do it may be something as follows.

You can start by splitting your text into lines.

var lines = text.split("\n");

Then you know that odd lines are URLs, and even lines are dog information.

List<JsonObject> objects = new ArrayList<>();
for(int i=0; i < lines.length; i++) {
  var line = lines[i];
  if(i % 2 == 0) {
     // apply regex solution given in the other answer
     // to extract the dog information
  } else {
    url = line;
    // since json objects are complete on odd lines
    // build json and add it to the list
    var jsonObject = ...;
    objects.add(jsonObject);
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.