/    /  Javascript json handling

Javascript json handling

 

JSON is derived from the JavaScript programming language. It is a natural choice to provide as a data format in JavaScript. JSON, short for JavaScript Object Notation, is provided like the name “Jason.”

Where we can use JSON in your JavaScript programs, some general use cases of JSON include:

Storing data.
Generating data structures from user input.
Passing data from server to client, client to server, and server to server.
Configuring and verifying data.

 

JSON Format:

 

JSON’s format is derived from JavaScript object syntax. But it is entirely text-based. The object is a key-value data format that is typically rendered in curly({}) braces.

 

EXAMPLE:

 

working with a .JSON file

 

{
"first_name" : "Sammy",
"last_name" : "Shark",
"online" : true
}

 

JSON object in a .js or .html file

 

var sammy = {
"first_name" : "Sammy",
"last_name" : "Shark",
"online" : true
}

 

all on one line:

 

var sammy = '{"first_name" : "Sammy", "last_name" : "Shark", "location" : "Ocean"}';

 

Converting JSON objects into strings can be particularly providing for passing data in a quick manner.

 

Functions for Working with JSON:

 

Two methods for stringifying and parsing JSON. Being able to convert JSON from object to string and vice versa is providing for transferring and storing data.

 

JSON.stringify():

 

This function converts an object to a JSON string.

The JSON object that we assign to the variable obj, and then convert it using JSON.stringify() by passing obj to the function. Assign this string to the variable s:

 

EXAMPLE:

 

var obj = {"first_name" : "Sammy", "last_name" : "Shark", "location" : "Ocean"}
var s = JSON.stringify(obj)

 

JSON.parse():

 

JSON.parse() within the context of an HTML file:

 

EXAMPLE:

 

<!DOCTYPE html>
<html>
<body>

<p id="user"></p>

<script>
var s = '{"first_name" : "Sammy", "last_name" : "Shark", "location" : "Ocean"}';

var obj = JSON.parse(s);

document.getElementById("user").innerHTML =
"Name: " + obj.first_name + " " + obj.last_name + "<br>" +
"Location: " + obj.location;
</script>

</body>
</html>

 

OUPTUT:

 

Name: Sammy Shark
Location: Ocean