安全地将JSON字符串转换为对象

时间:2022-01-21 06:48:14

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

给定一个JSON数据字符串,如何将该字符串安全地转换为JavaScript对象?

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.

…但是,这使得我们容易受到包含其他代码的json字符串的影响,简单地使用eval是非常危险的。

23 个解决方案

#1


1668  

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

只要您能保证浏览器相当现代,jsonString (jsonString)就是一种纯粹的JavaScript方法。

#2


850  

The jQuery method is now deprecated. Use this method instead:

jQuery方法现在已被弃用。使用这种方法:

let jsonObject = JSON.parse(jsonString);

Original answer using deprecated jQuery functionality:

原始答案使用废弃的jQuery功能:

If you're using jQuery just use:

如果您使用jQuery,请使用:

jQuery.parseJSON( jsonString );

It's exactly what you're looking for (see the jQuery documentation).

这正是您所需要的(请参阅jQuery文档)。

#3


136  

Edit: This answer is outdated and Jonathan's answer above (JSON.parse(jsonString)) is now the best answer.

编辑:这个答案已经过时了,上面乔纳森的答案(JSON.parse(jsonString))现在是最好的答案。

JSON.org has JSON parsers for many languages including 4 different ones for Javascript. I believe most people would consider json2.js their goto implementation.

org有许多语言的JSON解析器,包括4种不同的Javascript解析器。我相信大多数人会考虑json2。js他们转到实现。

#4


60  

Use simple code represented in the following link on MSDN.

使用在MSDN上的以下链接中表示的简单代码。

var jsontext = '{"firstname":"Jesper","surname":"Aaberg","phone":["555-0100","555-0120"]}';
var contact = JSON.parse(jsontext);

and reverse

和反向

var str = JSON.stringify(arr);

#5


17  

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

我不确定其他的方法,但这里是如何在Prototype中完成的(JSON教程)。

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.

当参数清理传入字符串时,使用true调用evalJSON()。

#6


15  

This seems to be the issue:

这似乎是问题所在:

An input is received, via ajax websocket etc, and it is always gonna be in String format - but you need to know if it is JSON.parsable. Touble is, that if you always run it through a JSON.parse, the program MAY continue 'successfully' but you'll still see an error thrown in the console with the dreaded "Error: unexpected token 'x'".

通过ajax websocket接收一个输入,它总是以字符串的形式出现——但是你需要知道它是否是JSON.parsable。Touble是,如果您总是通过JSON运行它。解析,程序可能继续“成功”,但您仍然会看到在控制台中抛出的错误,并带有可怕的“错误:意外令牌‘x’”。

var data;

try {
  data = JSON.parse(jqxhr.responseText);
} catch (_error) {}

data || (data = {
  message: 'Server error, please retry'
});

#7


11  

If you're using jQuery, you can also just do $.getJSON(url, function(data) { });

如果您正在使用jQuery,也可以使用$。getJSON(url、功能(数据){ });

Then you can do things like data.key1.something, data.key1.something_else, etc.

然后你可以做一些事情,比如data.key1。一些东西,data.key1。something_else等等。

#8


10  

$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: callback
});

The callback is passed the returned data, which will be a JavaScript object or array as defined by the JSON structure and parsed using the $.parseJSON() method.

回调函数传递返回的数据,它将是一个JavaScript对象或数组,由JSON结构定义,并使用$. parsejson()方法解析。

#9


9  

Just for fun, here is the way using function :

只是为了好玩,这里是使用函数的方式:

 jsonObject = (new Function('return ' + jsonFormatData))()

#10


8  

If you want this method can be used on this way.Here Data object which you want ex:Data='{result:true,count:1}'

如果你想这样做,可以用这个方法。这里需要的数据对象是: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 If you are working with serial port programing

如果您正在使用串口编程,这个方法对Nodejs非常有帮助

#11


6  

The easiest way using parse() method:

使用parse()方法最简单的方法是:

var response = '{"result":true,"count":1}';
var JsonObject= JSON.parse(response);

then you can get the values of the Json elements, for example:

然后您可以获得Json元素的值,例如:

var myResponseResult = JsonObject.result;
var myResponseCount = JsonObject.count;

Using jQuery as described in the documentation:

使用jQuery如文档所述:

JSON.parse(jsonString);

#12


5  

I have successfully been using json_sans_eval for a while now. According to its author, it is more secure than json2.js.

我已经成功地使用json_sans_eval有一段时间了。根据作者的说法,它比json2.js更安全。

#13


5  

Using JSON.parse is probably the best way. Here's an example live demo

使用JSON。解析可能是最好的方法。这是一个现场演示的例子

var jsonRes = '{ "students" : [' +
          '{ "firstName":"Michel" , "lastName":"John" ,"age":18},' +
          '{ "firstName":"Richard" , "lastName":"Joe","age":20 },' +
          '{ "firstName":"James" , "lastName":"Henry","age":15 } ]}';
var studentObject = JSON.parse(jsonRes);

#14


3  

I found a "better" way:

我找到了一种“更好”的方式:

In CoffeeScript:

CoffeeScript:

try data = JSON.parse(jqxhr.responseText)
data ||= { message: 'Server error, please retry' }

In Javascript:

在Javascript中:

var data;

try {
  data = JSON.parse(jqxhr.responseText);
} catch (_error) {}

data || (data = {
  message: 'Server error, please retry'
});

#15


1  

JSON.parse() converts any JSON String passed into the function, to a JSON Object.

parse()将传入函数的任何JSON字符串转换为JSON对象。

For Better understanding press F12 to open Inspect Element of your browser and go to console to write following commands : -

为了更好地理解,按F12打开浏览器的Inspect元素,并到控制台编写以下命令:-

var response = '{"result":true,"count":1}'; //sample json object(string form)
JSON.parse(response); //converts passed string to JSON Object.

Now run the command :-

现在运行命令:-

console.log(JSON.parse(response));

you'll get output as Object {result: true, count: 1}.

您将得到输出作为对象{result: true, count: 1}。

In order to use that Object, you can assign it to the variable let's say obj :-

为了使用这个对象,你可以把它赋给变量,比如说obj:-

var obj = JSON.parse(response);

Now by using obj and dot(.) operator you can access properties of the JSON Object.

现在,通过使用obj和dot(.)运算符,您可以访问JSON对象的属性。

Try to run the command

尝试运行命令

console.log(obj.result);

#16


1  

JSON.parse(jsonString);

json.parse will change into object.

json。解析将变为object。

#17


1  

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解析总是让人头疼,如果输入不像预期的那样,它会抛出错误并崩溃您正在做的事情。您可以使用下面的小函数来安全地解析输入。即使输入不是有效的,或者对于大多数情况来说已经是一个更好的对象,它也总是将对象转换为对象。

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 || {};
  }
};

#18


1  

Officially documented:

正式记录:

The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.

解析()方法解析JSON字符串,构造字符串描述的JavaScript值或对象。可以提供一个可选的修改函数,以便在返回结果对象之前对其执行转换。

Syntax

语法

JSON.parse(text[, reviver])

Parameters

参数

text

文本

The string to parse as JSON. See the JSON object for a description of JSON syntax.

解析为JSON的字符串。有关JSON语法的描述,请参见JSON对象。

reviver (optional)

兴奋剂(可选)

If a function, this prescribes how the value originally produced by parsing is transformed, before being returned.

如果是一个函数,它规定解析最初产生的值在返回之前是如何转换的。

Return value

返回值

The Object corresponding to the given JSON text.

与给定JSON文本对应的对象。

Exceptions

异常

Throws a SyntaxError exception if the string to parse is not valid JSON.

如果要解析的字符串不是有效的JSON,则抛出一个SyntaxError异常。

#19


1  

Converting the object to JSON, and then parsing it, works for me, like:

将对象转换为JSON,然后解析它,对我来说是可行的,比如:

JSON.parse(JSON.stringify(object))

#20


0  

You also can use reviver function to filter.

您也可以使用修改函数来过滤。

var data = JSON.parse(jsonString, function reviver(key, value) {
   //your code here to filter
});

for more information read JSON.parse

有关更多信息,请阅读JSON.parse。

#21


0  

Older question, I know, however nobody notice this solution by using new Function(), an anonymous function that returns the data.

但是,我知道,没有人通过使用new Function()注意到这个解决方案,new Function()是一个返回数据的匿名函数。


Just an example:

只是一个例子:

 var oData = 'test1:"This is my object",test2:"This is my object"';

 if( typeof oData !== 'object' )
  try {
   oData = (new Function('return {'+oData+'};'))();
  }
  catch(e) { oData=false; }

 if( typeof oData !== 'object' )
  { alert( 'Error in code' ); }
 else {
        alert( oData.test1 );
        alert( oData.test2 );
      }

This is a little more safe because it executes inside a function and do not compile in your code directly. So if there is a function declaration inside it, it will not be bound to the default window object.

这更安全一点,因为它在函数中执行,而不是在代码中直接编译。因此,如果其中有一个函数声明,它就不会被绑定到默认的窗口对象。

I use this to 'compile' configuration settings of DOM elements (for example the data attribute) simple and fast.

我用它来“编译”DOM元素(例如数据属性)的配置设置简单而快速。

#22


0  

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:

如果您的JavaScript在Mootools中,那么JSON就是。解析将被框架匿名。将JSON字符串安全地转换为对象的有效语法应该是:

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:

此外,JSON请求可以引发能够直接解析的对象。您可以在这里输入如何转换json原始数据:

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

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

#23


0  

Try this.This one is written in typescript.

试试这个。这个是用打字稿写的。

         export function safeJsonParse(str: string) {
               try {
                 return JSON.parse(str);
                   } catch (e) {
                 return str;
                 }
           }

#1


1668  

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

只要您能保证浏览器相当现代,jsonString (jsonString)就是一种纯粹的JavaScript方法。

#2


850  

The jQuery method is now deprecated. Use this method instead:

jQuery方法现在已被弃用。使用这种方法:

let jsonObject = JSON.parse(jsonString);

Original answer using deprecated jQuery functionality:

原始答案使用废弃的jQuery功能:

If you're using jQuery just use:

如果您使用jQuery,请使用:

jQuery.parseJSON( jsonString );

It's exactly what you're looking for (see the jQuery documentation).

这正是您所需要的(请参阅jQuery文档)。

#3


136  

Edit: This answer is outdated and Jonathan's answer above (JSON.parse(jsonString)) is now the best answer.

编辑:这个答案已经过时了,上面乔纳森的答案(JSON.parse(jsonString))现在是最好的答案。

JSON.org has JSON parsers for many languages including 4 different ones for Javascript. I believe most people would consider json2.js their goto implementation.

org有许多语言的JSON解析器,包括4种不同的Javascript解析器。我相信大多数人会考虑json2。js他们转到实现。

#4


60  

Use simple code represented in the following link on MSDN.

使用在MSDN上的以下链接中表示的简单代码。

var jsontext = '{"firstname":"Jesper","surname":"Aaberg","phone":["555-0100","555-0120"]}';
var contact = JSON.parse(jsontext);

and reverse

和反向

var str = JSON.stringify(arr);

#5


17  

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

我不确定其他的方法,但这里是如何在Prototype中完成的(JSON教程)。

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.

当参数清理传入字符串时,使用true调用evalJSON()。

#6


15  

This seems to be the issue:

这似乎是问题所在:

An input is received, via ajax websocket etc, and it is always gonna be in String format - but you need to know if it is JSON.parsable. Touble is, that if you always run it through a JSON.parse, the program MAY continue 'successfully' but you'll still see an error thrown in the console with the dreaded "Error: unexpected token 'x'".

通过ajax websocket接收一个输入,它总是以字符串的形式出现——但是你需要知道它是否是JSON.parsable。Touble是,如果您总是通过JSON运行它。解析,程序可能继续“成功”,但您仍然会看到在控制台中抛出的错误,并带有可怕的“错误:意外令牌‘x’”。

var data;

try {
  data = JSON.parse(jqxhr.responseText);
} catch (_error) {}

data || (data = {
  message: 'Server error, please retry'
});

#7


11  

If you're using jQuery, you can also just do $.getJSON(url, function(data) { });

如果您正在使用jQuery,也可以使用$。getJSON(url、功能(数据){ });

Then you can do things like data.key1.something, data.key1.something_else, etc.

然后你可以做一些事情,比如data.key1。一些东西,data.key1。something_else等等。

#8


10  

$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: callback
});

The callback is passed the returned data, which will be a JavaScript object or array as defined by the JSON structure and parsed using the $.parseJSON() method.

回调函数传递返回的数据,它将是一个JavaScript对象或数组,由JSON结构定义,并使用$. parsejson()方法解析。

#9


9  

Just for fun, here is the way using function :

只是为了好玩,这里是使用函数的方式:

 jsonObject = (new Function('return ' + jsonFormatData))()

#10


8  

If you want this method can be used on this way.Here Data object which you want ex:Data='{result:true,count:1}'

如果你想这样做,可以用这个方法。这里需要的数据对象是: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 If you are working with serial port programing

如果您正在使用串口编程,这个方法对Nodejs非常有帮助

#11


6  

The easiest way using parse() method:

使用parse()方法最简单的方法是:

var response = '{"result":true,"count":1}';
var JsonObject= JSON.parse(response);

then you can get the values of the Json elements, for example:

然后您可以获得Json元素的值,例如:

var myResponseResult = JsonObject.result;
var myResponseCount = JsonObject.count;

Using jQuery as described in the documentation:

使用jQuery如文档所述:

JSON.parse(jsonString);

#12


5  

I have successfully been using json_sans_eval for a while now. According to its author, it is more secure than json2.js.

我已经成功地使用json_sans_eval有一段时间了。根据作者的说法,它比json2.js更安全。

#13


5  

Using JSON.parse is probably the best way. Here's an example live demo

使用JSON。解析可能是最好的方法。这是一个现场演示的例子

var jsonRes = '{ "students" : [' +
          '{ "firstName":"Michel" , "lastName":"John" ,"age":18},' +
          '{ "firstName":"Richard" , "lastName":"Joe","age":20 },' +
          '{ "firstName":"James" , "lastName":"Henry","age":15 } ]}';
var studentObject = JSON.parse(jsonRes);

#14


3  

I found a "better" way:

我找到了一种“更好”的方式:

In CoffeeScript:

CoffeeScript:

try data = JSON.parse(jqxhr.responseText)
data ||= { message: 'Server error, please retry' }

In Javascript:

在Javascript中:

var data;

try {
  data = JSON.parse(jqxhr.responseText);
} catch (_error) {}

data || (data = {
  message: 'Server error, please retry'
});

#15


1  

JSON.parse() converts any JSON String passed into the function, to a JSON Object.

parse()将传入函数的任何JSON字符串转换为JSON对象。

For Better understanding press F12 to open Inspect Element of your browser and go to console to write following commands : -

为了更好地理解,按F12打开浏览器的Inspect元素,并到控制台编写以下命令:-

var response = '{"result":true,"count":1}'; //sample json object(string form)
JSON.parse(response); //converts passed string to JSON Object.

Now run the command :-

现在运行命令:-

console.log(JSON.parse(response));

you'll get output as Object {result: true, count: 1}.

您将得到输出作为对象{result: true, count: 1}。

In order to use that Object, you can assign it to the variable let's say obj :-

为了使用这个对象,你可以把它赋给变量,比如说obj:-

var obj = JSON.parse(response);

Now by using obj and dot(.) operator you can access properties of the JSON Object.

现在,通过使用obj和dot(.)运算符,您可以访问JSON对象的属性。

Try to run the command

尝试运行命令

console.log(obj.result);

#16


1  

JSON.parse(jsonString);

json.parse will change into object.

json。解析将变为object。

#17


1  

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解析总是让人头疼,如果输入不像预期的那样,它会抛出错误并崩溃您正在做的事情。您可以使用下面的小函数来安全地解析输入。即使输入不是有效的,或者对于大多数情况来说已经是一个更好的对象,它也总是将对象转换为对象。

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 || {};
  }
};

#18


1  

Officially documented:

正式记录:

The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.

解析()方法解析JSON字符串,构造字符串描述的JavaScript值或对象。可以提供一个可选的修改函数,以便在返回结果对象之前对其执行转换。

Syntax

语法

JSON.parse(text[, reviver])

Parameters

参数

text

文本

The string to parse as JSON. See the JSON object for a description of JSON syntax.

解析为JSON的字符串。有关JSON语法的描述,请参见JSON对象。

reviver (optional)

兴奋剂(可选)

If a function, this prescribes how the value originally produced by parsing is transformed, before being returned.

如果是一个函数,它规定解析最初产生的值在返回之前是如何转换的。

Return value

返回值

The Object corresponding to the given JSON text.

与给定JSON文本对应的对象。

Exceptions

异常

Throws a SyntaxError exception if the string to parse is not valid JSON.

如果要解析的字符串不是有效的JSON,则抛出一个SyntaxError异常。

#19


1  

Converting the object to JSON, and then parsing it, works for me, like:

将对象转换为JSON,然后解析它,对我来说是可行的,比如:

JSON.parse(JSON.stringify(object))

#20


0  

You also can use reviver function to filter.

您也可以使用修改函数来过滤。

var data = JSON.parse(jsonString, function reviver(key, value) {
   //your code here to filter
});

for more information read JSON.parse

有关更多信息,请阅读JSON.parse。

#21


0  

Older question, I know, however nobody notice this solution by using new Function(), an anonymous function that returns the data.

但是,我知道,没有人通过使用new Function()注意到这个解决方案,new Function()是一个返回数据的匿名函数。


Just an example:

只是一个例子:

 var oData = 'test1:"This is my object",test2:"This is my object"';

 if( typeof oData !== 'object' )
  try {
   oData = (new Function('return {'+oData+'};'))();
  }
  catch(e) { oData=false; }

 if( typeof oData !== 'object' )
  { alert( 'Error in code' ); }
 else {
        alert( oData.test1 );
        alert( oData.test2 );
      }

This is a little more safe because it executes inside a function and do not compile in your code directly. So if there is a function declaration inside it, it will not be bound to the default window object.

这更安全一点,因为它在函数中执行,而不是在代码中直接编译。因此,如果其中有一个函数声明,它就不会被绑定到默认的窗口对象。

I use this to 'compile' configuration settings of DOM elements (for example the data attribute) simple and fast.

我用它来“编译”DOM元素(例如数据属性)的配置设置简单而快速。

#22


0  

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:

如果您的JavaScript在Mootools中,那么JSON就是。解析将被框架匿名。将JSON字符串安全地转换为对象的有效语法应该是:

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:

此外,JSON请求可以引发能够直接解析的对象。您可以在这里输入如何转换json原始数据:

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

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

#23


0  

Try this.This one is written in typescript.

试试这个。这个是用打字稿写的。

         export function safeJsonParse(str: string) {
               try {
                 return JSON.parse(str);
                   } catch (e) {
                 return str;
                 }
           }