I have response from server that looks this way:
{"value1":1,"value2":45,"value3":"x"}
{"value1":1,"value2":45,"value3":"x"}
{"value1":1,"value2":45,"value3":"x"}
Response comes in text format.
Parse JSON doesn't work because of "Unexpected token {"
Please help me to convert this into valid object
UPDATE 1
Output of
const arr = `[${res.replaceAll('\n', ',')}]`
Is
[{"value1":1,"value2":45,"value3":"x"},
{"value1":1,"value2":45,"value3":"x"},
{"value1":1,"value2":45,"value3":"x"},]
Looks like a problem is in the last comma, when I'm copying res data manually, it doesn't happen.
UPDATE 2
In addition server response included invisible empty lines, that I didn't noticed and trim() fixed it
CodePudding user response:
First you should try to fix the problem on the server side. Only if that's not possible, you should fix the problem on the client side.
Your actual input text seems to be
{"value1":1,"value2":45,"value3":"x"}
{"value1":1,"value2":45,"value3":"x"}
{"value1":1,"value2":45,"value3":"x"}
with an empty line at the end.
You can trim the string (remove all whitespaces around it), replace the linebreaks with separators and wrap it all in square brackets. Then you can parse it as JSON:
JSON.parse(`[${res.trim().replaceAll('\n', ',')}]`)
That gives you an array of objects and you can work with it as usual.
Example
const res = `{"value1":1,"value2":45,"value3":"x"}
{"value1":1,"value2":45,"value3":"x"}
{"value1":1,"value2":45,"value3":"x"}`;
const arr = JSON.parse(`[${res.trim().replaceAll('\n', ',')}]`);
console.log(arr);
console.log(arr[1].value2);
CodePudding user response:
EDIT: I did not understand the question so here's a better answer:
const res = `{"value1":1,"value2":45,"value3":"x"}\n{"value1":1,"value2":45,"value3":"x"}\n{"value1":1,"value2":45,"value3":"x"}`;
const resArray = res.split("\n");
let realOutputArray = [];
resArray.forEach(res => {
let inputObject = JSON.parse(res);
let outputArray1 = [];
// loop through all the values in the object
for (const key in inputObject) {
// add the new value to the array
outputArray1.push(inputObject[key]);
}
realOutputArray.push(outputArray1);
});
console.log(realOutputArray); // is should output "[ [1, 2, 3, ...], [1, 2, 3, ...], ...]"