Reputation: 2366
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"}"
Upvotes: 0
Views: 164
Reputation: 1073978
There's String#replaceFirst
:
jsString = jsString.replaceFirst("^[^{]+", "");
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*", "");
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.
Upvotes: 3