-1

I am trying to parse json in JavaScript

var str = '{"id-1": "www.er.co.uk","id-2": "www.wer.co.uk","id-3": "wer.wer.com","id-4": "www.wwaer.co.uk"}';

var divWebsite = JSON.parse(str);

i am getting error (fiddle)

Uncaught SyntaxError: Unexpected token o

While at the same time my json is valid as you can see here http://jsonlint.com/ (sorry you will need to copy and past json)

Richerd fuld
  • 364
  • 1
  • 10
  • 23

3 Answers3

1

That's not JSON. You can see the difference:

http://jsfiddle.net/05dn7mpa/2/

So if you have an string with a json you can parse it. If you've got the propper vanilla object it's parsed !

  var divWebsite = JSON.parse('{    "id-1": "www.er.co.uk",    "id-2": "www.wer.co.uk",    "id-3": "wer.wer.com",    "id-4": "www.wwaer.co.uk"}');
Marcos Pérez Gude
  • 21,869
  • 4
  • 38
  • 69
1

In this case you need to pass a string to JSON.parse

HTML

<div id="parsed"></div>

JS

  var divWebsite = JSON.parse('{"id-1": "www.er.co.uk","id-2": "www.wer.co.uk","id-3": "wer.wer.com","id-4": "www.wwaer.co.uk"}');

  document.getElementById('parsed').innerHTML = divWebsite['id-1'];

JSFIDDLE

thedevlpr
  • 1,101
  • 12
  • 28
0

What you pass to JSON.parse() is not a string, that's why. You pass an object. In a typical scenario you want JSON.parse to return that object. What you should pass is a string.

If you want to get a json string out of that object use JSON.stringify()

dimlucas
  • 5,040
  • 7
  • 37
  • 54