Pase json in javascript

This question already has an answer here:

  • Safely turning a JSON string into an object 22 answers

  • 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"}');
    

    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


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

    链接地址: http://www.djcxy.com/p/31720.html

    上一篇: 如何将字符串转换为Javascript中的对象?

    下一篇: Pase json在javascript中