Skip to content

Instantly share code, notes, and snippets.

@mstorino
Last active October 16, 2017 19:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mstorino/0b1192cab6ae4fef1aac5c5ba56c0e29 to your computer and use it in GitHub Desktop.
Save mstorino/0b1192cab6ae4fef1aac5c5ba56c0e29 to your computer and use it in GitHub Desktop.
JSON Overview

JSON - JavaScript Object Notation

JSON is a data format.

It is easy for humans to edit / write & computers to parse / generate.

A common use of JSON is to exchange data to/from a web server.

Example library in JSON:

    {
          "myBooks": [
          
            {
                    "title" : "cloudy with a chance of meatballs",
                    "type": "kids"
            },
            {
                    "title" : "if hemingway wrote javascript",
                    "type": "code"
            }
          ] 
    }

Format

JSON is formatted like a Javascript object literal.

Property names and strings must be enclosed in double quotation marks.

Property values can be arrays or nested objects. Values can be numbers, booleans, null and undefined.

Property names and values are separated by a :colon to form name:value pair

A comma-separted list of name:value pairs is enclosed within {} braces to create a complete JavaSCript object.

GET Data

JSON data is transferred as text so you MUST convert JSON to objects / arrays that can be used in a JavaScript Program

The key to working with JSON is to convert it from a string to an object using the JSON.parse method.
Then you can access the properties or elements in the data using dot / bracket notation.

            {
                    "title" : "cloudy with a chance of meatballs",
                    "type": "kids"
            }
            var book = JSON.parse(response);
            book.title; // cloudy with a chance of meatballs
            book.type; // kids

POST (send) data

https://www.w3schools.com/js/js_json_stringify.asp

When sending data to a web server, the data has to be a string. Convert a JavaScript object into a string with JSON.stringify().

Javascript Object

var obj = { "name":"John", "age":30, "city":"New York"};

Use the JavaScript function JSON.stringify() to convert it into a string.

var myJSON = JSON.stringify(obj);

The result will be a string following the JSON notation.

    var obj = { "name":"John", "age":30, "city":"New York"};
    var myJSON = JSON.stringify(obj);
    document.getElementById("demo").innerHTML = myJSON; //{"name":"John","age":30,"city":"New York"}

Avoid using functions in JSON, the functions will lose their scope, and you would have to use eval() to convert them back into functions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment