0

I want to extract the value 0.81 from the following string, but I don't know how. Using JSON doesn't work, because as far as I know it's not proper JSON code.

[{"boundingbox":{"size":{"height":239.23,"width":239.23},"tl":{"y":46.15,"x":166.92}},"name":"152:0.81,","confidence":0.9}]

Do you have any idea how to do that?

1
  • 1
    It's valid json, but the 0.81 is not a value of its own. You need to get the value of "name", split it on ":", an take the second part of the split result. Should be a nice exercise so I am not gonna give a working answer. Commented Apr 14, 2013 at 21:39

2 Answers 2

1

If this is JSON, which it appears to be, load it up as a JSON Object and

JSONArray jsonArray = new JSONArray(thatString);
JSONObject jObj = jsonArray.getJSONObject(0);
String name = jObj.getString("name");

Which would then give you a string "152:0.81,", an odd name - however I would then split it:

String[] tokens = name.split(":");

tokens[0] will be 152

tokens[1] will be 0.81,

Sign up to request clarification or add additional context in comments.

Comments

0

It actually is valid Json, so you could use Json library (any of them), to load the Json to an Object and access the value - If you're having problems loading this into an Object, perhaps you can change your question and show us the error?

If, by any chance, you might get a response that isn't valid Json, you might use a regex:

If you always have that same pattern, something like:

\"name\":\"\d+:(\d\.\d+),\" 

Your value will be in capturing group one.

If you're not sure how to use regexes in Java, just search SO or Google, there's a ton of examples.

4 Comments

Good suggestion to fail-over to a regex when JSON parse finds invalid JSON.
I find it extremely hard to believe that any application's API that is producing JSON would sporadically produce invalid JSON. Sounds highly, highly unlikely to me.
Yes it's unbelievable but I have got many errors while parsing it in JSON. The 152 is dynamic how to change the regex to fit that, it's a variable.
@nickb Yes, it's unlikely, but I have no clue what API the OP is using.

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.