Reputation: 2790
I have the following JSON returned from an endpoint
{
"response": {
"lines": [
"[{'line':'3007621h7s2','type':'national'},{'line':'3007663f7s9','type':'international'}]",
"[{'line':'3007262p7f6','type':'national'},{'line':'3007262a0s1','type':'international'}]"
]
}
}
the property lines
is an array that should contain multiple arrays, however, as you can see, lines
is an array of strings. How can I make each element in the lines property to be an array of objects?
Thanks
Upvotes: 1
Views: 769
Reputation: 3965
The easiest way to convert the strings to arrays is to eval()
them.
var obj = {
"response": {
"lines": [
"[{'line':'3007621h7s2','type':'national'},{'line':'3007663f7s9','type':'international'}]",
"[{'line':'3007262p7f6','type':'national'},{'line':'3007262a0s1','type':'international'}]"
]
}
}
obj.response.lines = obj.response.lines.map(line => eval(line));
console.log(obj);
Upvotes: 1
Reputation: 7923
There are a couple of errors with your json (I dont know if that is the actual json or it was hardcoded so you might check it). The first one is
'line:'3007621h7s2
should be 'line':3007621h7s2
3007621h7s2
should be '3007621h7s2'
When you fix your json, then you can use JSON.parse()
to convert the string
var data = {
"response": {
"lines": [
"[{'line':'3007621h7s2', 'type': 'national'},{'line':'3007663f7s9','type':'international'}]",
"[{'line':'3007262p7f6', 'type': 'national'},{'line':'3007262a0s1','type':'international'}]"
]
}
}
data.response.lines = data.response.lines.map(a=>JSON.parse(a.replace(/'/g,'"')))
console.log(
data
)
Upvotes: 1