admin管理员组

文章数量:1323323

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

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

Share edited Nov 28, 2012 at 14:43 user441521 asked Nov 28, 2012 at 13:50 user441521user441521 6,99826 gold badges98 silver badges167 bronze badges 1
  • Tip, alternate ' and " characters. You don't have to escape ' or " if it is inside a string of "" or '' respectively. I.e. '[{"name":"name"},{"name":"Rick"}]' – Neil Commented Nov 28, 2012 at 13:55
Add a ment  | 

3 Answers 3

Reset to default 6

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"}]'.

I guess its sholuld e as:

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

If you lose the (escaped) quotes around the root elements you might get what you want.

E.g. something like

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

本文标签: javascriptJSONparse on array of JSON strings not doing as expectedStack Overflow