Alternatives to JavaScript eval() for parsing JSON

前端 未结 9 1260
忘了有多久
忘了有多久 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:40

    Well, safe or not, when you are using jQuery, you're better to use the $.getJSON() method, not $.ajax():

    $.getJSON(url, function(data){
        alert(data.exampleType);
    });
    

    eval() is usually considered safe for JSON parsing when you are only communicating with your own server and especially when you use a good JSON library on server side that guarantees that generated JSON will not contain anything nasty.

    Even Douglas Crockford, the author of JSON, said that you shouldn't use eval() anywhere in your code, except for parsing JSON. See the corresponding section in his book JavaScript: The Good Parts

    0 讨论(0)
  • 2020-12-01 08:45

    The alternative to evaluating the code is to parse it manually. It's not as hard as it sounds but it's quite a lot heavier at runtime. You can read about it here.

    The important part to note is evaluating JSON is not inherently insecure. As long as you trust the source not to balls things up. That includes making sure that things passed into the JSON encoder are properly escaped (to stop people 2 steps up the stream executing code on your users' machines).

    0 讨论(0)
  • 2020-12-01 08:47

    Unsafe? That depends on if you can trust the data.

    If you can trust that the string will be JSON (and won't include, for example, functions) then it is safe.

    That said - if you are using jQuery, why are you doing this manually? Use the dataType option to specify that it is JSON and let the library take care of it for you.

    0 讨论(0)
  • 2020-12-01 08:47

    Using JavaScript’s eval is unsafe. Because JSON is just a subset of JavaScript but JavaScript’s eval allows any valid JavaScript.

    Use a real JSON parser like the JSON parser from json.org instead.

    0 讨论(0)
  • 2020-12-01 08:51

    you can try it like this

    var object = new Function("return " + jsonString)()
    
    0 讨论(0)
  • 2020-12-01 08:57

    If you are using jQuery, as of version 1.4.1 you can use jQuery.parseJSON()

    See this answer: Safe json parsing with jquery?

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