Search code examples
javascriptarraysjsonstringstringify

Convert array of strings to array of objects in JSON property


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


Solution

  • 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);