Reliable and Recognized JavaScript Certification Online #

JSON data format

JSON (acronym from JavaScript Object Notation) is a lightweight data-interchange format. It is easy for human to read and write and easy for machines to parse and generate.
JSON is based on subset of JavaScript syntax. Though JSON is derived from JavaScript, it is a language-independent data format.
Nowadays JSON is very popular. It is used commonly for client – server communication and in RESTfull web services. JSON has significantly replaced XML.

JSON can represent strings, numbers, booleans, null, arrays (as ordered sequences of values) and objects (as key value pairs).

JSON object

JavaScript JSON object contains methods for parsing JSON and convert data to JSON format.

JSON.parse(text) – parses a JSON string and returns JavaScript value or object described by the string.

JSON.stringify(value) – converts JavaScript value or object to a JSON string.

Examples

Convert object to Json:

var shoppingCart = {
    items: [
        {id: 1, productName: 'bread', price: 3, quantity: 1},
        {id: 2, productName: 'cheese', price: 3.5, quantity: 2}
    ],
    total: 10,
    currency: 'EUR'
};

var shoppingCardJson = JSON.stringify(shoppingCart);

console.log(shoppingCardJson);
// output:
// {"items":[{"id":1,"productName":"bread","price":3,"quantity":1},{"id":2,"productName":"cheese","price":3.5,"quantity":2}],"total":10,"currency":"EUR"}

Parse JSON to object:

var productJson = '{"productId":1001, "productName": "camera", "price": 105.5, "available": true}';
var product = JSON.parse(productJson);

console.log(product);

// output:
// Object { productId: 1001, productName: "camera", price: 105.5, available: true }

No Comments

Reply