Actually I am doing some testing in which I am getting response from one of our endpoint which looks like multiple individual json objets and I need to convert them in such a form like a string or a single json object so that I can perform some action on them.
Json response Example :-
{"user_name":"testUser","email":"[email protected]"}
{"country":"Australia","Gender":"Male"}
{"type":"Customer_Account","membership":"Annual"}
Here the issue is I can not perform any operation until I convert it to some string or Json object.
And cannot control response as its coming from some third party application.
Any idea how to convert it using JavaScript or Java will be a great help.
CodePudding user response:
I think that your problem is in the source of the response, that is not a valid JSON. You can validate errors here: https://jsonlint.com/
Have you implemented the source of the JSON? If so you could make it a list of objects...
[{"user_name":"testUser","email":"[email protected]"},
{"country":"Australia","Gender":"Male"},
{"type":"Customer_Account","membership":"Annual"}]
If the source of the response is external (you can't modify it), it is possible to save the response into a String, then split the string into a list to iterate it to make the objects.
Hope this is somewhat helpful.
CodePudding user response:
If your objects are separated by line breaks, you can read the stream line by line, and parse each line that should be valid JSON.
Otherwise, you can detect the end of an object by keeping track of the level of nested braces (increment for {
, decrement for }
).
Instead of parsing each object separately, you can also insert brackets and commas to form a valid JSON array, and then parse that array.
CodePudding user response:
Split the JSONs using regex and keep it in an array:
let text = '{"user_name":"testUser","email":"[email protected]"}{"country":"Australia","Gender":"Male"}{"type":"Customer_Account","membership":"Annual"}';
const myArray = text.split(/(?=[{])/g);
let name = JSON.parse(myArray[0]).user_name;
console.log(myArray[0]);
console.log(name);
Now you can parse the strings as JSON.
CodePudding user response:
Join them with comma ,
and put result in brackets []
:
[
{"user_name":"testUser","email":"[email protected]"},
{"country":"Australia","Gender":"Male"},
{"type":"Customer_Account","membership":"Annual"}
]
after that use can use JSONObject class or other related things