0

I have a String variable that stores the literal text of a JavaScript object:

String jsString = "mainData = {"name":"John", "id":"12345"}"

Is there a JSON method (or any method) in Java that will remove the "mainData = " part of the string in order to leave only the JavaScript data? Something like this:

newString = someMethod(jsString);
JSONObject jsonObject = new JSONObject(newString); //newString = "{"name":"John", "id":"12345"}"

1 Answer 1

3

There's String#replaceFirst:

jsString = jsString.replaceFirst("^[^{]+", "");

Live Example

That will remove any characters as the start of the string prior to the first {. It makes the assumption that the string contains JSON where the outermost thing is an object (as opposed to an array or just a value), although it could readily be tweaked not to make that assumption. For instance, this version:

jsString = jsString.replaceFirst("^\\s*[A-Za-z0-9_$]+\\s*=\\s*", "");

Live Example

That removes a series of letters, numbers, _, or $, optionally surrounded by whitespace, and a following =, possibly followed by whitespace, at the beginning of the string. Now, that's not a complete list of valid JavaScript identifier characters (that list is long), but you get the idea.

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

1 Comment

Cool, I've never used Regex before so this is good to know. Also, I could've easily made a simple method of my own that will remove any characters before the first '{' or '[' but I was just curious if some specific JSON method in Java already existed that did this. Thanks for the detailed answer!

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.