Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON.parse on array of JSON strings not doing as expected

I'm new to javascript so learning how some of this stuff works.

I have a string that looks like: ["{\"name\":\"name\"}","{\"name\":\"Rick\"}"]

If I JSON.parse() that shouldn't it return an array of objects that have a property of name?

What I get is 2 elements in an array but they are just the JSON strings. They are not objects with property name. What am I missing?

[EDIT] I was calling stringify() on the object and then passing it to the array instead of just passing the object as is to the array. Then I stringify() the array. I was stringifying a stringify which caused it to put the escape characters :)

like image 444
user441521 Avatar asked Feb 18 '23 08:02

user441521


1 Answers

If I JSON.parse() that shouldn't it return an array of objects that have a property of name?

No, it looks like the JSON defines an array with two strings in it.

This is the JSON for an array with two strings in it:

[
    "{\"name\":\"name\"}",
    "{\"name\":\"Rick\"}"
]

In JavaScript string literal form, that's '["{\"name\":\"name\"}","{\"name\":\"Rick\"}"]'.

This is the JSON for an array with two objects in it:

[
    {
        "name": "name"
    },
    {
        "name": "Rick"
    }
]

In JavaScript string literal form, that would be '[{"name":"name"},{"name":"Rick"}]'.

like image 192
T.J. Crowder Avatar answered Mar 04 '23 00:03

T.J. Crowder