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

在我回显json_encoded数据并通过ajax检索它之后,我经常对何时应该使用JSON感到困惑。stringify和JSON.parse。

我得到[对象,对象]在我的控制台.log解析和JavaScript对象时stringized。

$.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?
    }
});

当前回答

JSON:主要用于与服务器交换数据。在发送之前 JSON对象给服务器,它必须是一个字符串。

JSON.stringify() //Converts the JSON object into the string representation.
var jsonData={"Name":"ABC","Dept":"Software"};// It is a JSON object
var jsonString=JSON.stringify(jsonData);// It is a string representation of the object
// jsonString === '{"Name":"ABC","Dept":"Software"}'; is true

它还将Javascript数组转换为字符串

var arrayObject=["ABC","Software"];// It is array object
var arrString=JSON.stringify(array);// It is string representation of the array (object)
// arrString === '["ABC","Software"]'; is true 

当我们从服务器接收到JSON数据时,数据将是字符串格式。因此,我们将字符串转换为JSON对象。

JSON.parse() //To convert the string into JSON object.
var data='{ "name":"ABC", "Dept":"Software"}'// it is a string (even though it looks like an object)
var JsonData= JSON.parse(data);// It is a JSON Object representation of the string.
// JsonData === { "name":"ABC", "Dept":"Software"}; is true

其他回答

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

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

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

JSON:主要用于与服务器交换数据。在发送之前 JSON对象给服务器,它必须是一个字符串。

JSON.stringify() //Converts the JSON object into the string representation.
var jsonData={"Name":"ABC","Dept":"Software"};// It is a JSON object
var jsonString=JSON.stringify(jsonData);// It is a string representation of the object
// jsonString === '{"Name":"ABC","Dept":"Software"}'; is true

它还将Javascript数组转换为字符串

var arrayObject=["ABC","Software"];// It is array object
var arrString=JSON.stringify(array);// It is string representation of the array (object)
// arrString === '["ABC","Software"]'; is true 

当我们从服务器接收到JSON数据时,数据将是字符串格式。因此,我们将字符串转换为JSON对象。

JSON.parse() //To convert the string into JSON object.
var data='{ "name":"ABC", "Dept":"Software"}'// it is a string (even though it looks like an object)
var JsonData= JSON.parse(data);// It is a JSON Object representation of the string.
// JsonData === { "name":"ABC", "Dept":"Software"}; is true

他们是完全相反的。

JSON.parse()用于解析作为JSON接收的数据;它将JSON字符串反序列化为JavaScript对象。

另一方面,JSON.stringify()用于从对象或数组中创建JSON字符串;它将JavaScript对象序列化为JSON字符串。

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

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