1

Supposed I have a string that contains JSON:

{"foo":"bar"}

Then I can easily parse this using the JSON.parse function.

Now supposed the string has some additional prefix, such as:

blah: {"foo":"bar"}

Then simply using JSON.parse does not work, of course. What I'd need to do is to extract a substring and then run the function. Now supposed I do not know the content or the length of the prefix (i.e., I don't know whether it finishes with a colon and a space, or whether it is always six characters long, or …): What is the best way to parse the contained JSON?

The most obvious way would probably be to just find the index of the first {, but this won't work if the string itself contains a {.

Is there a better, i.e. more reliable, way to do this?

3
  • i think there is no such intelligence provided to us ( or i don't know) ... so that u can remove the unwanted/unpredicted string and find the valid json to parse... the other thing you can do is... search for the substring index of {" and "} ... suppose int indexOfStartOfJson=indexof( {" ); int indexOfEndOfJson=indexof( "} ); and now substring your string ... i.e String validJson=substring(indexOfStartOfJson,indexOfEndOfJson); Commented Oct 12, 2015 at 13:49
  • Try indexOf("{"), lastIndexOf("}"), and substring...? Commented Oct 12, 2015 at 13:52
  • @BNK This is what I already said I could do, but I was looking for better options ;-) Commented Oct 12, 2015 at 13:57

2 Answers 2

2

You may want to use replace to remove the prefix, something like:

test = 'blah: {"foo":"bar"}';
test = test.replace(/^.*?{/, "{");
alert(test);

The above regex works with:

blah: {"foo":"bar"}
blah{"foo":"bar"}
blah:{"foo":"bar"}
blah {"foo":"bar"}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the snippet, but as said I do not know whether there is always a space in the end, hence this check won't work for all cases.
Just make the space optional, ?. I'll update the regex.
1

If you don't know anything about the prefix, I guess you might have to remove one character at a time and try parsing the remainder as JSON. As soon as you succeed, you'll have found the starting point.

If the parsing fails a SyntaxError will be thrown which you'll obviously have to handle.

2 Comments

This works, but probably is quite slow… but anyway, thanks for suggesting this!
Yeah, definitely a last resort, both style wise and performance wise :)

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.