JavaScript. Intro to JSON

Home » Tutorials » JavaScript » JavaScript. Intro to JSON
In this lesson we will consider JSON data format. Why must we use data formats.Simply we need it to exchange data betweeen for example php and javascript or between two different servers. A few lessons later we will get data from VK server.
JavaScript has got JSON object with two methods – stringify and parse.
JSON.stringify() turns js object into json string.
JSON.parse() parse json string into js object.

Code lesson (JSON file)

{"name":"Иван","age":26,"birthday":{"year":1990,"month":"июнь","day":29}}

Code lesson

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>JSON</title>
</head>
<body>


	<script>
		// JSON - JavaScript Object Notation

		var kamil = {name: "Камиль", age:27}
		//			{"name":"Камиль","age":27}
		console.log(kamil);

		console.log(JSON.stringify(kamil));

		var ivan = {
			name: "Иван",
			age: 26,
			birthday: {
				year: 1990,
				month: "июнь",
				day: 29
			}
		};

		// {"name":"Иван","age":26,"birthday":{"year":1990,"month":"июнь","day":29}}
		console.log(JSON.stringify(ivan));

		var john = {
			name: "John",
			age: 26,
			sayHi: function(){
				console.log(this.name);
			}
		}

		//	{"name":"John","age":26}
		console.log(JSON.stringify(john));

		var oreilly = {
			name: 'O\'Reilly'
		};

		console.log(JSON.stringify(oreilly));	

		//stringify - превращает объект в json
		//parse	 - парсит (разбирает) json строку...


		var jsonStr = '{"name":"Иван","age":26,"birthday":{"year":1990,"month":"июнь","day":29}}';

		var res = JSON.parse(jsonStr);

		console.log(res);

		document.write(res.name + "\n\r");
		document.write(res.birthday.month);


	</script>


</body>
</html>

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.

Pin It on Pinterest

Share This