0

I have a string response like below which is a invalid json as it contains "obj13=".I want to convert it to a JSONObject(JAVA) and use it.Is there any good way to convert it to JSONObject without using String split operation.

obj13={
  players: [
    {
      name: "rocky",
      place: "brazil",
      age: "21",
    },
    {
      name: "andy",
      place: "New Zealand",
      age: "23",
    }
  ]
}
7
  • 2
    What's wrong with splitting off the bogus prefix? Commented Aug 29, 2013 at 16:58
  • @HotLicks I can just use eval(String) in javascript to convert the mention string to objects and use them.I thought maybe there would be something equivalent in JAVA which can handle such json response. Commented Aug 29, 2013 at 17:01
  • You can always write your own JSON parser, or grab an open source one and modify it. Aside from that there is no way to do what you want. Java is not Javascript. Commented Aug 29, 2013 at 17:05
  • 1
    It should be noted that, even after the prefix is removed, what's left is not legal JSON, since the keys are not quoted. But I think many/most parsers can be made to tolerate this. Commented Aug 29, 2013 at 18:10
  • 1
    @HotLicks: And the extraneous commas on the last object property are not valid JSON either. Commented Aug 29, 2013 at 18:32

1 Answer 1

1

This is, of course, JavaScript, not JSON. If you can, I would go back to the service provider and ask for a JSON response.

If the format of the string is consistent, you could just use:

json=json.substring(json.indexof('=')+1);  

and then parse the result. Note that most good parsers should have an option to allow the keywords without quotes and to allow the extraneous commas (mine does, but unfortunately for you it doesn't create JSONObject's but is of a lower level - it's designed to construct the data-structure of the caller's choice, which could be a JSONObject if that's what you wanted but you'd have to code it).

If the result may or may not have the assignment, you may want to get a bit fancier and ensure that the non-whitespace characters before the '=' are valid for a JS identifier and the first non-whitespace after it is '{'.

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

1 Comment

There may be a parser somewhere that can be convinced that "=" should be treated as ":", so that if you wrapped the whole thing with {} it would parse. But it's just as easy to truncate the string as to wrap it.

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.