1

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

4
  • There is a typo on your code. 'line:'3007621h7s2 should be 'line':'3007621h7s2' Commented Sep 28, 2018 at 14:55
  • The error is that your backend is json-encoding each line in a first step. You should not try to fix in the frontend the mistakes/bugs of your backend. Commented Sep 28, 2018 at 14:58
  • @Thomas that's true but let me be more clear: I don't have access to the server code so i can't modify what the response is going to be. So I'll update my question specifying that. So there is no way to do it once I get it in the front-end? Commented Sep 28, 2018 at 15:00
  • thanks @LuisfelipeDejesusMunoz I fixed the typo Commented Sep 28, 2018 at 15:01

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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
  • Values like 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
)

1 Comment

Yes, they were typos. I just fixed them, so I'll try your code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.