Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.stringify and JSON.parse .

(在我回显我的json_encoded数据并通过ajax将其检索回来之后,我经常会对何时应该使用JSON.stringifyJSON.parse感到困惑。)

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

(我在解析时在我的console.log中获取[object,object] ,在字符串化时获得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?
    }
});
  ask by HIRA THAKUR translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
251 views
Welcome To Ask or Share your Answers For Others

1 Answer

JSON.stringify turns 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.parse turns 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" 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...