最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JSON.parse, what am I doing wrong? - Stack Overflow

programmeradmin2浏览0评论

So, I'm trying to parse some JSON in Javascript. This feels like it should work, but I'm getting an error. Here's the function call:

JSON.parse("{player: 'green', direction: 'north'}");

And here's the error

VM156:1 Uncaught SyntaxError: Unexpected token p in JSON at position 1
    at Object.parse (native)
    at <anonymous>:1:6

I'm trying this on an empty web page, no JS libraries are present.

The string, just executed as Javascript creates an object with the two expected attributes.

I've tried wrapping the keys in strings. That didn't parse.

The unexpected token appears to be whatever the first letter is.

What am I doing wrong, how can I parse this object?

So, I'm trying to parse some JSON in Javascript. This feels like it should work, but I'm getting an error. Here's the function call:

JSON.parse("{player: 'green', direction: 'north'}");

And here's the error

VM156:1 Uncaught SyntaxError: Unexpected token p in JSON at position 1
    at Object.parse (native)
    at <anonymous>:1:6

I'm trying this on an empty web page, no JS libraries are present.

The string, just executed as Javascript creates an object with the two expected attributes.

I've tried wrapping the keys in strings. That didn't parse.

The unexpected token appears to be whatever the first letter is.

What am I doing wrong, how can I parse this object?

Share Improve this question asked Oct 31, 2016 at 19:08 AJFaradayAJFaraday 2,4501 gold badge20 silver badges41 bronze badges 5
  • 5 You're not passing it JSON, which is a problem for a function expecting JSON – adeneo Commented Oct 31, 2016 at 19:09
  • @adeneo Possiblyt this doesn't do what I expect. Can you give a valid example? – AJFaraday Commented Oct 31, 2016 at 19:09
  • 4 jsonlint. is your friend, as is the spec at json – Quentin Commented Oct 31, 2016 at 19:10
  • 9 In JSON, keys and values are quoted with doublequotes, always, unless the values are numbers or other "objects" etc. – adeneo Commented Oct 31, 2016 at 19:10
  • Keep in mind that JSON is more strict than javascript notation when creating objects. – S. Buda Commented Oct 31, 2016 at 22:51
Add a ment  | 

1 Answer 1

Reset to default 15

That's not valid JSON.

Try this:

JSON.parse('{"player": "green", "direction": "north"}');

Note the double quotes " instead of single quotes ' and the quotes around the object keys.

发布评论

评论列表(0)

  1. 暂无评论