JSON.stringify 和 JSON.parse 的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17785592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 19:58:25  来源:igfitidea点击:

Difference between JSON.stringify and JSON.parse

javascriptjson

提问by HIRA THAKUR

I have been confused over when to use these two parsing methods.

我一直对何时使用这两种解析方法感到困惑。

After I echo my json_encoded data and retrieve it back via ajax, I often run into confusion about when I should use JSON.stringifyand JSON.parse.

在我回显我的 json_encoded 数据并通过 ajax 检索它之后,我经常遇到关于何时应该使用JSON.stringifyJSON.parse 的困惑。

I get [object,object]in my console.logwhen parsed and a JavaScript object when stringified.

[object,object]在解析时进入我的console.log并在字符串化时进入一个 JavaScript 对象。

$.ajax({
url: "demo_test.txt",
success: function(data) {
         console.log(JSON.stringify(data))
                     /* OR */
         console.log(JSON.parse(data))
        //this is what I am unsure about?
    }
});

回答by Quentin

JSON.stringifyturns a JavaScript object into JSON text and stores that JSON text in a string, eg:

JSON.stringify将 JavaScript 对象转换为 JSON 文本并将该 JSON 文本存储在字符串中,例如:

var my_object = { key_1: "some text", key_2: true, key_3: 5 };

var object_as_string = JSON.stringify(my_object);  
// "{"key_1":"some text","key_2":true,"key_3":5}"  

typeof(object_as_string);  
// "string"  

JSON.parseturns a string of JSON text into a JavaScript object, eg:

JSON.parse将一串 JSON 文本转换为 JavaScript 对象,例如:

var object_as_string_as_object = JSON.parse(object_as_string);  
// {key_1: "some text", key_2: true, key_3: 5} 

typeof(object_as_string_as_object);  
// "object" 

回答by Bjorn 'Bjeaurn' S

JSON.parse()is for "parsing" something that was received as JSON.
JSON.stringify()is to create a JSON string out of an object/array.

JSON.parse()用于“解析”作为 JSON 接收的内容。
JSON.stringify()是从对象/数组中创建一个 JSON 字符串。

回答by bluehallu

They are the inverse of each other. JSON.stringify()serializes a JS object into a JSON string, whereas JSON.parse()will deserialize a JSON string into a JS object.

它们互为倒数。JSON.stringify()将 JS 对象序列化为 JSON 字符串,而JSON.parse()将 JSON 字符串反序列化为 JS 对象。

回答by Bhushan Gadekar

They are the opposites of each other.

他们是彼此的对立面。

JSON.stringify()

JSON.stringify()

JSON.stringify() serializes a JS object or value into a JSON string.

JSON.stringify() 将 JS 对象或值序列化为 JSON 字符串。

JSON.stringify({});                  // '{}'
JSON.stringify(true);                // 'true'
JSON.stringify('foo');               // '"foo"'
JSON.stringify([1, 'false', false]); // '[1,"false",false]'
JSON.stringify({ x: 5 });            // '{"x":5}'

JSON.stringify(new Date(2006, 0, 2, 15, 4, 5)) 
// '"2006-01-02T15:04:05.000Z"'

JSON.stringify({ x: 5, y: 6 });
// '{"x":5,"y":6}' or '{"y":6,"x":5}'
JSON.stringify([new Number(1), new String('false'), new Boolean(false)]);
// '[1,"false",false]'

JSON.parse()

JSON.parse()

The JSON.parse() method parses a string as JSON, optionally transforming the value produced.

JSON.parse() 方法将字符串解析为 JSON,可选择转换生成的值。

JSON.parse('{}');              // {}
JSON.parse('true');            // true
JSON.parse('"foo"');           // "foo"
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
JSON.parse('null');            // null

回答by Mou

Firstly, JSON.stringify()function converts a JavaScript value to a JavaScript Object Notation (JSON) string. JSON.parse()function converts a JavaScript Object Notation (JSON) string into an object. For more information about these two functions, please refer to the following links.

首先,JSON.stringify()函数将 JavaScript 值转换为 JavaScript Object Notation (JSON) 字符串。JSON.parse()函数将 JavaScript 对象表示法 (JSON) 字符串转换为对象。有关这两个功能的更多信息,请参阅以下链接。

https://msdn.microsoft.com/library/cc836459(v=vs.94).aspxhttps://msdn.microsoft.com/library/cc836466(v=vs.94).aspx

https://msdn.microsoft.com/library/cc836459(v=vs.94).aspx https://msdn.microsoft.com/library/cc836466(v=vs.94).aspx

Secondly, the following sample will be helpful for you to understand these two functions.

其次,下面的示例将有助于您理解这两个功能。

<form id="form1" runat="server">
    <div>
        <div id="result"></div>
    </div>
</form>

<script>
    $(function () {
        //define a json object
        var employee = { "name": "John Johnson", "street": "Oslo West 16", "phone": "555 1234567" };

        //use JSON.stringify to convert it to json string
        var jsonstring = JSON.stringify(employee);
        $("#result").append('<p>json string: ' + jsonstring + '</p>');

        //convert json string to json object using JSON.parse function
        var jsonobject = JSON.parse(jsonstring);
        var info = '<ul><li>Name:' + jsonobject.name + '</li><li>Street:' + jsonobject.street + '</li><li>Phone:' + jsonobject.phone + '</li></ul>';

        $("#result").append('<p>json object:</p>');
        $("#result").append(info);
    });
</script>

回答by king neo

var log = { "page": window.location.href, 
        "item": "item", 
        "action": "action" };

log = JSON.stringify(log);
console.log(log);
console.log(JSON.parse(log));

//The output will be:

//输出将是:

//For 1st Console is a String Like:

//对于第一个控制台是一个字符串,例如:

'{ "page": window.location.href,"item": "item","action": "action" }'

//For 2nd Console is a Object Like:

//对于第二个控制台是一个对象,如:

Object {
page   : window.location.href,  
item   : "item",
action : "action" }

回答by Patrick

The real confusion here is not about parse vs stringify, it's about the data type of the dataparameter of the success callback.

这里真正的混淆不是关于 parse 和 stringify,而是关于data成功回调参数的数据类型。

datacan be either the raw response, i.e a string, or it can be an JavaScript object, as per the documentation:

data根据文档,可以是原始响应,即字符串,也可以是 JavaScript 对象:

success

Type: Function( Anything data, String textStatus, jqXHR jqXHR ) A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter or the dataFilter callback function, if specified;<..>

成功

类型:Function(Anything data, String textStatus, jqXHR jqXHR) 请求成功时调用的函数。该函数传递三个参数: 从服务器返回的数据,根据 dataType 参数或 dataFilter 回调函数(如果指定)进行格式化;<..>

And the dataType defaults to a setting of 'intelligent guess'

并且 dataType 默认设置为“智能猜测”

dataType (default: Intelligent Guess (xml, json, script, or html))

Type: String The type of data that you're expecting back from the server. If none is specified, jQuery will try to inferit based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).

数据类型(默认:智能猜测(xml、json、脚本或 html))

类型:字符串 您期望从服务器返回的数据类型。如果没有指定,jQuery 将尝试根据响应的 MIME 类型推断它(XML MIME 类型将产生 XML,在 1.4 中 JSON 将产生一个 JavaScript 对象,在 1.4 脚本中将执行脚本,其他任何类型都将以字符串形式返回)。

回答by Hamed Kamrava

JSON.stringify()Converts an object into a string.

JSON.stringify()将对象转换为字符串。

JSON.parse()Converts a JSON string into an object.

JSON.parse()将 JSON 字符串转换为对象。

回答by P. Brown

I don't know if it's been mentioned, but one of the uses of JSON.parse(JSON.stringify(myObject)) is to create a clone of the original object.

我不知道是否有人提到过,但 JSON.parse(JSON.stringify(myObject)) 的用途之一是创建原始对象的克隆。

This is handy when you want to mess with some data without affecting the original object. Probably not the cleanest / fastest way but certainly the simplest for objects that aren't massively complex.

当您想在不影响原始对象的情况下处理某些数据时,这很方便。可能不是最干净/最快的方法,但对于不是非常复杂的对象来说肯定是最简单的。

回答by Zigri2612

JavaScript Object <-> JSON String

JavaScript 对象 <-> JSON 字符串



JSON.stringify() <-> JSON.parse()


JSON.stringify(obj) - Takes any serializable object and returns the JSON representation as a string.

JSON.stringify(obj) - 接受任何可序列化的对象并以字符串形式返回 JSON 表示。

JSON.stringify() -> Object To String.

JSON.parse(string) - Takes a well formed JSON string and returns the corresponding JavaScript object.

JSON.parse(string) - 采用格式良好的 JSON 字符串并返回相应的 JavaScript 对象。

JSON.parse() -> String To Object.

Explanation:JSON.stringify(obj [, replacer [, space]]);

说明:JSON.stringify(obj [, replacer [, space]]);

Replacer/Space - optional or takes integer value or you can call interger type return function.

Replacer/Space - 可选或采用整数值,或者您可以调用整数类型返回函数。

function replacer(key, value) {
    if (typeof value === 'number' && !isFinite(value)) {
        return String(value);
    }
    return value;
}
  • Replacer Just Use for replace non finite no with null.
  • Space use for indenting Json String by space
  • Replacer Just 用于用 null 替换非有限的 no。
  • 用于按空格缩进 Json 字符串的空间使用