Safely turning a JSON string into an object

2018-12-30 23:56发布

Given a string of JSON data, how can you safely turn that string into a JavaScript object?

Obviously you can do this unsafely with something like...

var obj = eval("(" + json + ')');

...but that leaves us vulnerable to the json string containing other code, which it seems very dangerous to simply eval.

24条回答
宁负流年不负卿
2楼-- · 2018-12-31 00:26

JSON parsing is always pain in ass. If the input is not as expected it throws an error and crashes what you are doing. You can use the following tiny function to safely parse your input. It always turns an object even if the input is not valid or is already an object which is better for most cases.

JSON.safeParse = function (input, def) {
  // Convert null to empty object
  if (!input) {
    return def || {};
  } else if (Object.prototype.toString.call(input) === '[object Object]') {
    return input;
  }
  try {
    return JSON.parse(input);
  } catch (e) {
    return def || {};
  }
};
查看更多
忆尘夕之涩
3楼-- · 2018-12-31 00:26

Try this.This one is written in typescript.

         export function safeJsonParse(str: string) {
               try {
                 return JSON.parse(str);
                   } catch (e) {
                 return str;
                 }
           }
查看更多
若你有天会懂
4楼-- · 2018-12-31 00:27

JSON.parse(jsonString) is a pure JavaScript approach so long as you can guarantee a reasonably modern browser.

查看更多
何处买醉
5楼-- · 2018-12-31 00:27

If your JavaScript are in Mootools the JSON.parse will be Anonymous by the Framework.
A valid syntax to safely turning a JSON string into an object shall be:

var object = JSON.decode(string[, secure]);

Moreover a JSON Request is can raise an object that able to parse directly.
You may cek how it turn a json raw data here:

http://jsfiddle.net/chetabahana/qbx9b5pm/

查看更多
刘海飞了
6楼-- · 2018-12-31 00:28

I'm not sure about other ways to do it but here's how you do it in Prototype (JSON tutorial).

new Ajax.Request('/some_url', {
  method:'get',
  requestHeaders: {Accept: 'application/json'},
  onSuccess: function(transport){
    var json = transport.responseText.evalJSON(true);
  }
});

Calling evalJSON() with true as the argument sanitizes the incoming string.

查看更多
余生请多指教
7楼-- · 2018-12-31 00:28

Try using the method with this Data object. ex:Data='{result:true,count:1}'

try {
  eval('var obj=' + Data);
  console.log(obj.count);
}
catch(e) {
  console.log(e.message);
}

This method really helps in Nodejs when you are working with serial port programming

查看更多
登录 后发表回答