JSON Parsing (PPT) (1)
JSON Parsing (PPT) (1)
JSON
Parsing
JSON Parsing
By Vandita JavaScript Object Notation(JSON)
Roll no: 8
Parsing
JSON.parse()
• A common use of JSON is to exchange data to/from a
web server.
• When receiving data from a web server, the data is
always a string.
• Parse the data with JSON.parse(), and the data
becomes a JavaScript object.
Given the JSON string:
'{"name":"John", "age":30, "city":"New York"}'
--> This JSON object represents a person with three
properties: name, age, and city.
Use the JavaScript function JSON.parse() to
convert text into a JavaScript object:
JSON Parsing
const jsonString = '{"name": "John", "age": 30, "city":
"New York"}';
const obj = JSON.parse(jsonString);
console.log(obj.name); // Output: John
console.log(obj.age); // Output: 30
console.log(obj.city); // Output: New York
Parsing in JSON refers to the process of converting a JSON string, which is a text
representation of data, into a corresponding data structure that a programming
language can use. For example, in JavaScript, parsing JSON means converting a JSON
string into a JavaScript object.
JSON Syntax:
Keys and string values in JSON are enclosed in double quotes.
Example:
{
"name": "John",
"age": 30,
JSON Parsing
"city": "New York"
}
Note: The text is in JSON format, or else you will get a syntax error.
4
Example:
<!DOCTYPE html>
<html>
<body>
<h2>Creating an Object from a JSON String</h2>
<p id="demo"></p>
<script>
const txt = '{"name":"John", "age":30, "city":"New York"}'
const obj = JSON.parse(txt);
document.getElementById("demo").innerHTML = obj.name + ", " + obj.age;
</script>
JSON Parsing
</body>
</html>
Output:
Example:
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
const text = '[ "Ford", "BMW", "Audi", "Fiat" ]';
JSON Parsing
const myArr = JSON.parse(text);
document.getElementById("demo").innerHTML = myArr[0];
</script>
</body>
</html>
Output: Ford
THANK YOU