How to convert Invalid JSON String to JSONObject in Java? - java

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",
}
]
}

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 '{'.

Related

Put missing double quotes in a JSON string value in java

I have a json string where all the values need to be surrounded with double quotes. for example (just a sample, it contains many similar fields)
{"Id": "2017",
"Currency": "AUD",
"Date": 2020-06-22,
"InCash": 0.000,
"Dep": "ABC90",
"sumCash": 770.87,
"AnotherDate": 2020-06-21}
to
{"Id": "2017",
"Currency": "AUD",
"Date": "2020-06-22",
"startCash": "0.000",
"Dep": "ABC90",
"sumCash": "770.87",
"AnotherDate": "2020-06-21"}
I am trying with regular expressions but its breaking the 'Date' fields.
jsonString.replaceAll(":[ ]*([\\w#\\.]+)", ": \"$1\"")
also tried with gson library, but its only putting the quotes on date values and not on the decimal values.
new JsonParser().parse(jsonString).toString()
What exactly I need to do to achieve it?
check this out
var newS = jsonString.replaceAll(": +((?!\\\\).*)(!?[,|}] *)", ": \"$1\"$2").replaceAll("\\\"\\\"","\"");
output
{
"Id": "2017",
"Currency": "AUD",
"Date": "2020-06-22",
"InCash": "0.000",
"Dep": "ABC90",
"sumCash": "770.87",
"AnotherDate": "2020-06-21"
}
if the other JSON form (rules) of yuior string don't change, this will work for the
name - value form.
note - i did not do the part where it could be a string in a list but its doable alsero
Find:
("\s*\w+\s*"\s*:(?!\s*")(?!\s*\d+\s*(?:,|\]|}))(?!\s*[{\[])(?!\s*(?:true|false|null)\s*(?:,|\]|}))\s*)(.+?)(?=[,}])
Replace:
$1"$2"
demo
see my complete PCRE regex for parsing JSON a eally simple structure spec.
here https://regex101.com/r/H8datD/1 which is not available to java until regex engine uses recursion (functions).
note - when needing to change just one aspect of JSON where it otherwise is complient with the spec structure
it is easy to extract the code in my regex to get right down to the area of interest. it easy !
Got it working with the below regex expression.
jsonString.replaceAll(": [ ]*([\\w#\\.-]+)", ": \"$1\""));
Thanks everyone for your help and support !

I am having trouble with some basic JSON parsing

The return from an external application is an Input Stream that looks like this:
JSONObj = {
"output":
[
{
"box":[0, 44, 43, 189],
"text":"~9 000 -"
}
]
}
I'm having trouble parsing the JSON in Java
The 'JSONOBJ' keeps coming back as an Invalid Token.
Is there a way to simply begin parsing at the '['?
I would advice against manipulating the JSON prior to parsing it. If you want to cut out parts it's a sign that your target data structure (the Java class you're intending to get) does not match the data you're receiving. These two should be in sync.
Throwing this into any decent JSON parser will tell you that this is invalid JSON.
Particularily, at line 6, you should remove the manual line breaks, since JSON only permits explicit ones using the line seperator \n:
{
"output": [
{
"box": [
0,
44,
43,
189
],
"text": "~9 000 -"
}
]
}
The easiest way might be:
json = json.substring(json.indexOf('{'))
And I actually disagree with Nicktar's statement, since that external program isn't even returning valid JSON (and I'd consider it a very very stupid implementation to be frank). There is no need in saying "hey, that's an object" because that's actually implicit. If a JSON starts with {, it's an object, if it starts with [, it's an array.

Get a dump of a section (object) of JSON

I'm looking to dump, rather toString() a section of JSON that I want to store locally as a string, since it it is highly variable and not imperative for me to know the contents.
I'm using JsonReader for the parsing:
https://developer.android.com/reference/android/util/JsonReader.html
Unfortunately, when I reach the token that contains what I want to dump, JsonReader does not have a method for dumping the entire JSON to a string.
This is the closest that it has:
https://developer.android.com/reference/android/util/JsonReader.html#toString()
It seems that I may have to use regex to pull out the value of the token I am targeting.
Is there another, better solution? How would I do this with regex?
Assume that this is the sample JSON and I am targeting the user key:
{
"id": 912345678901,
"text": "How do I read JSON on Android?",
"geo": null,
"user": {
"name": "android_newb",
"followers_count": 41
}
}

parsing a string by regular expression

I have a string of
"name"=>"3B Ae", "note"=>"Test fddd \"33 Ae\" FIXME", "is_on"=>"keke, baba"
and i want to parse it by a java program into segments of
name
3B Ae
note
Test fddd \"33 Ae\" FIXME
is_on
keke, baba
It is noted that the contents of the string, i.e. name, 3B Ae, are not fixed.
Any suggestion?
If you:
replace => with :
Wrap the full string with {}
The result will look like this, which is valid JSON. You can then use a JSON parser (GSON or Jackson, for example) to parse those values into a java object.
{
"name": "3B Ae",
"note": "Test fddd \"33 Ae\" FIXME",
"is_on": "keke, baba"
}
If you have control over the process that produces this string, I highly recommend that you use a standard format like JSON or XML that can be parsed more easily on the other end.
Because of the quoting rules, I'm not certain that a regular expression (even a PCRE with negative lookbehinds) can parse this consistently. What you probably want is to use a pushdown automaton, or some other parser capable of handling a context-free language.
If you can make sure your data (key or value) does not have a => or a , (or find some other delimiters that will not occur), the solution is pretty simple:
Split the string by , you get the key => value pairs
Split the key value => pairs by => you get what you want
if inputString holds
"name"=>"3B Ae", "note"=>"Test fddd \"33 Ae\" FIXME", "is_on"=>"keke baba"
(from a file for instance)
(I have changed the , to ; from between keke and baba)
String[] keyValuePairs = inputString.split(",");
for(String oneKeyValue : keyValuePairs)
{
String[] keyAndValue = oneKeyValue.split("=>");
}

What is the proper format for a JSON Response?

I've worked with several different APIs where I needed to parse JSON. And in all cases the Response is constructed a bit differently.
I now need to expose some data via a JSON API and want to know the proper way to deliver that Response.
Here is an example of what I have now, however some users (one using Java) are having difficulty parsing.
{"status": "200 OK",
"code": "\/api\/status\/ok",
"result": {
"publishers": ["Asmodee", "HOBBITY.eu", "Kaissa Chess & Games"],
"playing_time": 30, "description": "2010 Spiel des Jahres WinnerOne player is the storyteller for the turn. He looks at the 6 images in his hand. From one of these, he makes up a sentence and says it out loud (without showing the card to the other players).The other players select amongst their 6 images the one that best matches the sentence made up by the storyteller.Then, each of them gives their selected card to the storyteller, without showing it to the others. The storyteller shuffles his card with all the received cards. ",
"expansions": ["Dixit 2", "Dixit 2: \"Gift\" Promo Card", "Dixit 2: The American Promo Card", "Dixit Odyssey"],
"age": 8,
"min_players": 3,
"mid": "\/m\/0cn_gq3",
"max_players": null,
"designers": ["Jean-Louis Roubira"],
"year_published": 2008,
"name": "Dixit"
}
}
The Java user in particular is complaining that they get the error:
org.json.JSONException:[json string] of type org.json.JSONObject cannot be converted to JSONArray
But in Python I am able to take in this Response, fetch "result" and then parse as I would any other JSON data.
* UPDATE *
I passed both my JSON and Twitter's timeline JSON to JSONLint. Both are valid. The Java user can parse Twitter's JSON but not mine. What I noticed with Twitter's JSON is that it's encapsulated with brackets [], signifying an array. And the error this user is getting with my JSON is that it cannot be converted to a JSON array. I didn't think I need to encapsulate in brackets.
It looks valid according to http://json.parser.online.fr/ (random json parser). Its in the other code i'd say ;)
How exactly are you generating this response? Are you doing it yourself?
I see you have a dangling comma at the end of the last element in publishers (i.e. after the value Kaissa Chess & Games).
I'd recommend using JSONLint to ensure your JSON is valid.

Categories