Join the Stack Overflow Community
Stack Overflow is a community of 6.4 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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.

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

$.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?
    }
});
share|improve this question
35  
i knew it,there would be many other people just like me..searching for quick solution..i am sure this is not off topic any more when there are 1000+ people searching for the same thing..vote to reopen if you feel it can help other programmers.. – Leonardo Da Codinchi Nov 11 '13 at 19:47
29  
really cannot understand why this question was closed. it is a legitimate programming question which almost 6000 programmers in 5 months have sought the answer to. it ranks highly on Google for JSON stringify keywords, and has a very helpful top answer. sigh – verbumSapienti Jan 6 '14 at 16:35
7  
In particular, the close reason is inapplicable, as the question is not asking for code. Given the edit times, this may have been a fix put in after the question was closed, but it looks like a fully viable question now (and a reasonably popular one) and really ought to be reopened. As far as what Google said about it, this question is what Google said about it. – Ben Barden Feb 26 '14 at 17:44
    
To sum up the answers below: 1. They are the inverse of each other. 2. combined it helps to validate the data or turn human readable: json.stringify(json.parse(data)). – Hafenkranich Oct 7 at 22:35

14 Answers 14

up vote 400 down vote accepted

JSON.stringify turns a Javascript object into JSON text and stores that JSON text in a string.

JSON.parse turns a string of JSON text into a Javascript object.

share|improve this answer
6  
json.stringify(json.parse(data))?i saw this in code...so this is basically converting json data in to object and then again reconverting it to json data.. – Leonardo Da Codinchi Jul 22 '13 at 11:00
13  
@MESSIAH — Yes. It's largely pointless, but might serve as a JSON validator. – Quentin Jul 22 '13 at 11:01
11  
@Quentin Or as a JSON formatter. – user529758 Jul 22 '13 at 11:10
5  
Can also be used a simple object copy for object key value pairings. – hunterc Nov 21 '13 at 20:36
2  
I have found it very useful for debugging in the console - it makes it easily readable. – kirgy Jan 2 '14 at 14:59

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

share|improve this answer
3  
precision : it might not be an object. – Denys Séguret Jul 22 '13 at 10:50
    
True, could also be an array or anything Javascript recognizes as a certain type. Bottomline; it takes it and converts it to the appropriate JSON equivalent. – Bjorn Schijff Jul 22 '13 at 10:51
2  
@dystroy — It has to be an object (noting that an arrays are objects). – Quentin Jul 22 '13 at 10:51
2  
@quentin JSON.stringify(3) – Denys Séguret Jul 22 '13 at 11:01
    
@dystroy — huh, didn't realize they'd expanded it to deal with JSON fragments. That's unintuitive. – Quentin Jul 22 '13 at 11:03

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.

share|improve this answer

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.

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>
share|improve this answer

They are the opposites of each other.

JSON.stringify()

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

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()

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

JSON.parse('{}');              // {}
JSON.parse('true');            // true
JSON.parse('"foo"');           // "foo"
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
JSON.parse('null');            // null
share|improve this answer
    
A better name for parse() would be objectify() or jsonify(). – nu everest Sep 16 at 4:05
    
Why not JSON.toString() and JSON.toObject()? I would prefer these names (especially useful for new programmers that use intellisense). – Richard Chassereau Sep 26 at 0:24
    
you could have post developer.mozilla.org/en/docs/Web/JavaScript/Reference/… instead of copying – Mahi Nov 24 at 9:53

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

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

share|improve this answer
23  
This adds absolutely nothing that wasn't already said. – patricksweeney May 21 '15 at 16:04

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

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

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;<..>

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

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 infer it 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).

share|improve this answer
1  
This is a very useful addition, because it helps understand what the confusion is all about! – rmcsharry Sep 13 at 8:15

JSON.stringify(obj [, replacer [, space]]) - Takes any serializable object and returns the JSON representation as a string.

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

share|improve this answer

JavaScript Object <-> JSON String


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

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

JSON.stringify() -> Object To String.

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

JSON.parse() -> String To Object.

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

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

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
share|improve this answer

They are the complete opposite of each other.

JSON.parse() is used for parsing data that was received as JSON; it deserializes a JSON string into a JavaScript object.

JSON.stringify() on the other hand is used to create a JSON string out of an object or array; it serializes a JavaScript object into a JSON string.

share|improve this answer

JSON.parse() - is used to convert String to Object. JSON.stringify() - is used to convert Object to String.

You can refer this too...

<script type="text/javascript">

function ajax_get_json(){

    var hr = new XMLHttpRequest();
    hr.open("GET", "JSON/mylist.json", true);
    hr.setRequestHeader("Content-type", "application/json",true);
    hr.onreadystatechange = function() {
        if(hr.readyState == 4 && hr.status == 200) {
           /*  var return_data = hr.responseText; */

           var data=JSON.parse(hr.responseText);
           var status=document.getElementById("status");
           status.innerHTML = "";
           /* status.innerHTML=data.u1.country;  */
           for(var obj in data)
               {
               status.innerHTML+=data[obj].uname+" is in "+data[obj].country+"<br/>";
               }

        }
    }
    hr.send(null);
    status.innerHTML = "requesting...";
}
</script>
share|improve this answer
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":"http://localhost/test.html","item":"document loaded","action":"starting","details"}

//For 2nd Console is a Object Like:

Object {
page   :"http://localhost/test.html"    
action : "starting"
item   :"document loaded" }
share|improve this answer

They are opposing each other. JSON.Stringify() converts JSON to string and JSON.Parse() parses a string into JSON.

share|improve this answer

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.

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.