Alternatives to JavaScript eval() for parsing JSON

前端 未结 9 1261
忘了有多久
忘了有多久 2020-12-01 08:23

Quick Question. Eval in JavaScript is unsafe is it not? I have a JSON object as a string and I need to turn it into an actual object so I can obtain the data:



        
相关标签:
9条回答
  • 2020-12-01 08:58

    Another great alternative is YUI: http://yuilibrary.com/yui/docs/json/

    So your code would be something like:

    Y.JSON.parse('{"id": 15, "name": "something"}');
    
    0 讨论(0)
  • 2020-12-01 08:59

    You should use JSON and write JSON.parse.

    "Manual" parsing is too slow, so JSON.parse implementation from the library checks stuff and then ends up using eval, so it is still unsafe. But, if you are using a newer browser (IE8 or Firefox), the library code is not actually executed. Instead, native browser support kicks in, and then you are safe.

    Read more here and here.

    0 讨论(0)
  • 2020-12-01 09:02

    If you can't trust the source, then you're correct...eval is unsafe. It could be used to inject code into your pages.

    Check out this link for a safer alternative:

    JSON in Javascript

    The page explains why eval is unsafe and provides a link to a JSON parser at the bottom of the page.

    0 讨论(0)
提交回复
热议问题