天天看點

json對象表示法_JSON簡介(JavaScript對象表示法)

json對象表示法

JSON

stands for

JavaScript Object Notation

and is a very popular light-weight interchangeable format of data used today. Writing and reading

JSON

data is very convenient. It's also very easy to generate

JSON data

and parse it into strings, objects, etc. If you're familiar with hashmaps in C++ STL, JSON can be described as a hashmap C++ equivalent for JavaScript since it's based on key-value pairs. It is essentially a string that looks like a JavaScript object.

JSON

代表

JavaScript Object Notation,

并且是當今使用的非常流行的輕量級可互換格式。 寫入和讀取

JSON

資料非常友善。 生成

JSON資料

并将其解析為字元串,對象等也非常容易。如果您熟悉C ++ STL中的哈希圖,則JSON可描述為JavaScript的哈希圖C ++等效項,因為它基于鍵值對。 它本質上是一個看起來像JavaScript對象的字元串。

Sample code: 樣例代碼:
{
	"id": "0001",
	"type": "donut",
	"name": "Cake",
	"ppu": 0.55,
	"batters":
		{
			"batter":
				[
					{ "id": "1001", "type": "Regular" },
					{ "id": "1002", "type": "Chocolate" },
					{ "id": "1003", "type": "Blueberry" },
					{ "id": "1004", "type": "Devil's Food" }
				]
		},
	"topping":
		[
			{ "id": "5001", "type": "None" },
			{ "id": "5002", "type": "Glazed" },
			{ "id": "5005", "type": "Sugar" },
			{ "id": "5007", "type": "Powdered Sugar" },
			{ "id": "5006", "type": "Chocolate with Sprinkles" },
			{ "id": "5003", "type": "Chocolate" },
			{ "id": "5004", "type": "Maple" }
		]
}
           

Above is

an example of JSON data

, one can see

how JSON data looks like

, how it is essentially a string with key-value pairs but looks completely like a JavaScript object.

上面是

JSON資料的示例

,可以看到

JSON資料的樣子

,它本質上是具有鍵值對的字元串,但看起來卻完全像JavaScript對象。

Most of the API's or servers return

JSON data

as a response. That response is highly nested and organized so that the frontend developer can consume it easily as per her needs.

大多數API或伺服器都會傳回

JSON資料

作為響應。 該響應是高度嵌套和有組織的,是以前端開發人員可以根據自己的需求輕松使用它。

We'll use a fake rest API available https://jsonplaceholder.typicode.com/ for seeing how to work with JSON data. Head over to the website and copy the URL https://jsonplaceholder.typicode.com/todos/. We'll make a GET request to this URL and see the JSON response we get back. You can also see various endpoints of this API at https://jsonplaceholder.typicode.com/ but here we'll be using https://jsonplaceholder.typicode.com/todos/ endpoint that returns us a load of JSON data.

我們将使用https://jsonplaceholder.typicode.com/提供的僞造的rest API,以了解如何處理JSON資料。 轉到網站并複制URL https://jsonplaceholder.typicode.com/todos/ 。 我們将對此URL進行GET請求,并檢視傳回的JSON響應。 您還可以在https://jsonplaceholder.typicode.com/上看到此API的各種端點,但是這裡我們将使用https://jsonplaceholder.typicode.com/todos/端點,該端點将向我們傳回JSON資料的負載。

Create a simple

index.html

file and link it to

app.js

,

建立一個簡單的

index.html

檔案并将其連結到

app.js

<html >

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>JSON Data</title>
</head>

<body>
    <h1>JSON Data</h1>

    <script src="app.js"></script>
</body>

</html>
           

Now to go

app.js

and send a GET request to the URL,

現在轉到

app.js

并将GET請求發送到URL,

var request = new XMLHttpRequest();
request.onreadystatechange = function() {
    if (request.reayState === 4 && request.status === 200) {
        document.write(request.responseText);
    } else {
        console.log('Error occurred!');
    }

}
request.open('GET', 'https://jsonplaceholder.typicode.com/todos/');
request.send();
           

Now run your

index.html

by right clicking it and selecting open with chrome or directly running the live server. You will see some congested data on the screen. This is because our

JSON data

is unorganised and not indented properly. If you're using chrome, install the chrome extension

JSONView

from here,

現在,通過右鍵單擊

index.html

并選擇使用chrome打開或直接運作實時伺服器來運作它。 您将在螢幕上看到一些擁塞的資料。 這是因為我們的

JSON資料

是無組織的,并且縮進不正确。 如果您使用的是chrome,請從此處安裝chrome擴充名

JSONView

https://chrome.google.com/webstore/detail/jsonview/chklaanhfefbnpoihckbnefhakgolnmc?hl=en

https://chrome.google.com/webstore/detail/jsonview/chklaanhfefbnpoihckbnefhakgolnmc?hl=zh-CN

Now run your

index.html

file again and click the extension icon. You can now properly see the JSON response data that we got back from the API,

現在,再次運作

index.html

檔案,然後單擊擴充圖示。 現在,您可以正确地看到我們從API傳回的JSON響應資料,

[[
	{
	userId: 1,
	id: 1,
	title: "delectus aut autem",
	completed: false
	},
	{
	userId: 1,
	id: 2,
	title: "quis ut nam facilis et officia qui",
	completed: false
	},
	{
	userId: 1,
	id: 3,
	title: "fugiat veniam minus",
	completed: false
	},
	{
	userId: 1,
	id: 4,
	title: "et porro tempora",
	completed: true
	},
	{
	userId: 1,
	id: 5,
	title: "laboriosam mollitia et enim quasi adipisci quia provident illum",
	completed: false
	},
	{
	userId: 1,
	id: 6,
	title: "qui ullam ratione quibusdam voluptatem quia omnis",
	completed: false
	},
	{
	userId: 1,
	id: 7,
	title: "illo expedita consequatur quia in",
	completed: false
	},
	{
	userId: 1,
	id: 8,
	title: "quo adipisci enim quam ut ab",
	completed: true
	},
	{
	userId: 1,
	id: 9,
	title: "molestiae perspiciatis ipsa",
	completed: false
	},
	{
	userId: 1,
	id: 10,
	title: "illo est ratione doloremque quia maiores aut",
	completed: true
	},
	{
	userId: 1,
	id: 11,
	title: "vero rerum temporibus dolor",
	completed: true
	},
	{
	userId: 1,
	id: 12,
	title: "ipsa repellendus fugit nisi",
	completed: true
	},
	{
	userId: 1,
	id: 13,
	title: "et doloremque nulla",
	completed: false
	},
	{
	userId: 1,
	id: 14,
	title: "repellendus sunt dolores architecto voluptatum",
	completed: true
	},
	{
	userId: 1,
	id: 15,
	title: "ab voluptatum amet voluptas",
	completed: true
	},
	{
	userId: 1,
	id: 16,
	title: "accusamus eos facilis sint et aut voluptatem",
	completed: true
	},
	{
	userId: 3,
	id: 45,
	title: "velit soluta adipisci molestias reiciendis harum",
	completed: false
	},
...
]
           

It looks something like above. In the

request.open() method

, change the url by adding

'1'

at the end of the endpoint.

看起來像上面的東西。 在

request.open()方法中

,通過在端點的末尾添加

“ 1”來

更改URL。

request.open('GET','https://jsonplaceholder.typicode.com/todos/1');
           

Now we get a single item back,

現在我們拿回一件物品,

{ "userId": 1, "id": 1, "title": "delectus aut autem", "completed": false }
           

We can convert JSON to an array of objects using

JSON.parse()

and convert that array back to a string using

JSON.stringify()

. Syntactically, everything in JSON is in quotes. It is widely used today because of its similarity and compatibility with JavaScript.

我們可以使用

JSON.parse()

将JSON轉換為對象數組,并使用

JSON.stringify()

将該數組轉換回字元串。 從文法上講,JSON中的所有内容都用引号引起來。 由于它與JavaScript的相似性和相容性,是以如今已被廣泛使用。

翻譯自: https://www.includehelp.com/json/introduction-to-json-javascript-object-notation.aspx

json對象表示法