Speed up development with full-stack environments for every branch.

Learn More

How to serialize JSON to a string [JavaScript]

Forked from How to upload a file using jQuery.

3656 Runs 61977 Views 12502 Copies

How to serialize JSON to a string

Saved

Saved

lribeiro 90

lribeiro
published 4 years ago

<!DOCTYPE HTML>
<html>
<head>
  <meta charset="utf-8">
  <title>How to parse a JSON String</title>
  
  <!-- Load json2.js to support really old browsers -->
  <script src="js/json2.js"></script>
 
</head>

<body>
  
  <script>
    // Create a plain old javascript object 
    var deepObject = {
        "user" : {
          "name": "Luís Landeiro Ribeiro",
          "age": 28,
          "sex": "M",
          "interests": [ "Technology", "Mountain Biking", "People" ]
        }
    };
    
    /* From the official documentation
        JSON.stringify(value, replacer, space)
            value       any JavaScript value, usually an object or array.

            replacer    an optional parameter that determines how object
                        values are stringified for objects. It can be a
                        function or an array of strings.

            space       an optional parameter that specifies the indentation
                        of nested structures. If it is omitted, the text will
                        be packed without extra whitespace. If it is a number,
                        it will specify the number of spaces to indent at each
                        level. If it is a string (such as '\t' or '&nbsp;'),
                        it contains the characters used to indent at each level.
                        */
   
   /* Calling JSON.stringify will serialize the first parameter "deepObject" into a string, 
        null replacer means to use the JSON default to string converter,   
        4 to ensure each identation is made by 4 spaces
    */
    var identedText = JSON.stringify(deepObject,null,4);
    
    /* output the serialized JSON with pretty print */
    document.write("<h1>Idented 4 spaces</h1> <pre>"+identedText+"</pre>");
    
    /* Create a string serialization of the "deepObject" JS Oject */
    var jsonString = JSON.stringify(deepObject);
    
    /* ouput the JSON string to html */
    document.write("<h1>Unidented</h1> <pre>"+jsonString+"</pre>");
    
    /* Convert the jsonString into Javascript object */
    var newObject = JSON.parse(jsonString);
    
    /* output the javascript object to HTML */
    document.write("<h1>JS Object</h1>" + newObject);
    
    /* output the name of the user, calling js methods on the recently serialized object */
    document.write("<h1>User name</h1>" + newObject.user.name);
    
  </script>
</body> 
</html>
Please login/signup to get access to the terminal.

Your session has timed out.

Dismiss (the page may not function properly).