Basic structure
JSON is built on two structures:
1. A collection of name/value pairs. In different languages, it is understood as an object, a record, a struct, a dictionary, a hash table, a keyed list, or an associative array. array).
2. An ordered list of values. In most languages, it is understood as an array.
Basic Example
Simply put, JSON can convert a set of data represented in a JavaScript object into a string, and then you can easily pass this string between functions, or convert characters in an asynchronous application The string is passed from the Web client to the server-side program. This string looks a little weird, but JavaScript can easily interpret it, and JSON can represent more complex structures than "name/value pairs". For example, arrays and complex objects can be represented rather than just simple lists of keys and values.
Represents a name/value pair
In its simplest form, a "name/value pair" can be represented by the following JSON: { "firstName": "Brett" }
This example is very basic and actually Takes up more space than the equivalent plain text name/value pair: firstName=Brett
However, JSON comes into its own when multiple name/value pairs are strung together. First, you can create a record containing multiple "name/value pairs", such as:
{ "firstName": "Brett", "lastName": "McLaughlin", "email": "aaaa" }
From a syntax perspective At first glance, this isn't a huge advantage over name/value pairs, but in this case JSON is easier to use and more readable. For example, it makes it clear that the above three values ??are part of the same record; the curly braces make the values ??somehow related.
Representing an array
When it is necessary to represent a set of values, JSON can not only improve readability, but also reduce complexity. For example, suppose you want to represent a list of people's names. In XML, many start and end tags are required; if you use typical name/value pairs (like the ones you saw in previous articles in this series), a proprietary data format must be created , or change the key name to the form person1-firstName.
If using JSON, just group multiple records together with curly braces:
{ "people": [ { "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" }, { "firstName": "Jason", "lastName":"Hunter", "email": "bbbb"}, { "firstName": "Elliotte", "lastName":"Harold", "email": "cccc" } ]}
This is easy to understand. In this example, there is only one variable called people, and the value is an array of three entries, each entry being a record for a person containing a first name, last name, and email address. The above example demonstrates how to use parentheses to combine records into a single value. Of course, multiple values ??(each containing multiple records) can be represented using the same syntax:
{ "programmers": [ { "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" }, { "firstName": "Jason", "lastName":"Hunter", "email": "bbbb" }, { "firstName": "Elliotte", "lastName":"Harold", "email": "cccc" } ], "authors": [ { "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" }, { "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" }, { "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" } ], "musicians": [ { "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" }, { "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" } ] }
The most notable thing here is the ability to represent multiple values, each of which in turn contains multiple values. However, it should also be noted that the actual name/value pairs in the record can differ between different main entries (programmers, authors, and musicians). JSON is fully dynamic, allowing the way data is represented to change in the middle of the JSON structure.
There are no predefined constraints that need to be followed when processing data in JSON format. Therefore, within the same data structure, the way the data is represented can be changed, and the same thing can even be represented in different ways.
Format Application
After mastering the JSON format, using it in JavaScript is very simple. JSON is a native JavaScript format, which means that processing JSON data in JavaScript does not require any special API or toolkit.
Assigning JSON data to a variable
For example, you can create a new JavaScript variable and assign the JSON formatted data string directly to it:
var people = { "programmers": [ { "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" }, { "firstName": "Jason", "lastName":"Hunter", "email": "bbbb" }, { "firstName": "Elliotte", "lastName":"Harold", "email": "cccc" } ], "authors": [ { "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" }, { "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" }, { "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" } ], "musicians": [ { "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" }, { "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" } ] }
This is very simple; now people contains the JSON seen earlier format data. However, this isn't enough as the way to access the data doesn't seem obvious yet.
Access data
盡管看起來(lái)不明顯,但是上面的長(zhǎng)字符串實(shí)際上只是一個(gè)數(shù)組;將這個(gè)數(shù)組放進(jìn) JavaScript 變量之后,就可以很輕松地訪問它。實(shí)際上,只需用點(diǎn)號(hào)表示法來(lái)表示數(shù)組元素。所以,要想訪問 programmers 列表的第一個(gè)條目的姓氏,只需在 JavaScript 中使用下面這樣的代碼:
people.programmers[0].lastName;
注意,數(shù)組索引是從零開始的。所以,這行代碼首先訪問 people變量中的數(shù)據(jù);然后移動(dòng)到稱為 programmers的條目,再移動(dòng)到第一個(gè)記錄([0]);最后,訪問 lastName鍵的值。結(jié)果是字符串值 “McLaughlin”。
下面是使用同一變量的幾個(gè)示例。
people.authors[1].genre // Value is "fantasy" people.musicians[3].lastName // Undefined. This refers to the fourth entry, and there isn't one people.programmers[2].firstName // Value is "Elliotte"
利用這樣的語(yǔ)法,可以處理任何 JSON 格式的數(shù)據(jù),而不需要使用任何額外的 JavaScript 工具包或 API。
修改 JSON 數(shù)據(jù)
正如可以用點(diǎn)號(hào)和括號(hào)訪問數(shù)據(jù),也可以按照同樣的方式輕松地修改數(shù)據(jù):
people.musicians[1].lastName = "Rachmaninov";
在將字符串轉(zhuǎn)換為 JavaScript 對(duì)象之后,就可以像這樣修改變量中的數(shù)據(jù)。
轉(zhuǎn)換回字符串
當(dāng)然,如果不能輕松地將對(duì)象轉(zhuǎn)換回本文提到的文本格式,那么所有數(shù)據(jù)修改都沒有太大的價(jià)值。在 JavaScript 中這種轉(zhuǎn)換也很簡(jiǎn)單:
String newJSONtext = people.toJSONString();
這樣就行了!現(xiàn)在就獲得了一個(gè)可以在任何地方使用的文本字符串,例如,可以將它用作 Ajax 應(yīng)用程序中的請(qǐng)求字符串。
更重要的是,可以將任何JavaScript 對(duì)象轉(zhuǎn)換為 JSON 文本。并非只能處理原來(lái)用 JSON 字符串賦值的變量。為了對(duì)名為 myObject的對(duì)象進(jìn)行轉(zhuǎn)換,只需執(zhí)行相同形式的命令:
String myObjectInJSON = myObject.toJSONString();
這就是 JSON 與本系列討論的其他數(shù)據(jù)格式之間最大的差異。如果使用 JSON,只需調(diào)用一個(gè)簡(jiǎn)單的函數(shù),就可以獲得經(jīng)過(guò)格式化的數(shù)據(jù),可以直接使用了。對(duì)于其他數(shù)據(jù)格式,需要在原始數(shù)據(jù)和格式化數(shù)據(jù)之間進(jìn)行轉(zhuǎn)換。即使使用 Document Object Model 這樣的 API(提供了將自己的數(shù)據(jù)結(jié)構(gòu)轉(zhuǎn)換為文本的函數(shù)),也需要學(xué)習(xí)這個(gè) API 并使用 API 的對(duì)象,而不是使用原生的 JavaScript 對(duì)象和語(yǔ)法。
最終結(jié)論是,如果要處理大量 JavaScript 對(duì)象,那么 JSON 幾乎肯定是一個(gè)好選擇,這樣就可以輕松地將數(shù)據(jù)轉(zhuǎn)換為可以在請(qǐng)求中發(fā)送給服務(wù)器端程序的格式。
概念比較
JSON和XML的比較
◆可讀性
JSON和XML的可讀性可謂不相上下,一邊是簡(jiǎn)易的語(yǔ)法,一邊是規(guī)范的標(biāo)簽形式,很難分出勝負(fù)。
◆可擴(kuò)展性
XML天生有很好的擴(kuò)展性,JSON當(dāng)然也有,沒有什么是XML能擴(kuò)展,而JSON卻不能。不過(guò)JSON在Javascript主場(chǎng)作戰(zhàn),可以存儲(chǔ)Javascript復(fù)合對(duì)象,有著xml不可比擬的優(yōu)勢(shì)。
◆編碼難度
XML有豐富的編碼工具,比如Dom4j、JDom等,JSON也有提供的工具。無(wú)工具的情況下,相信熟練的開發(fā)人員一樣能很快的寫出想要的xml文檔和JSON字符串,不過(guò),xml文檔要多很多結(jié)構(gòu)上的字符。
◆解碼難度
XML的解析方式有兩種:
一是通過(guò)文檔模型解析,也就是通過(guò)父標(biāo)簽索引出一組標(biāo)記。例如:xmlData.getElementsByTagName("tagName"),但是這樣是要在預(yù)先知道文檔結(jié)構(gòu)的情況下使用,無(wú)法進(jìn)行通用的封裝。
另外一種方法是遍歷節(jié)點(diǎn)(document 以及 childNodes)。這個(gè)可以通過(guò)遞歸來(lái)實(shí)現(xiàn),不過(guò)解析出來(lái)的數(shù)據(jù)仍舊是形式各異,往往也不能滿足預(yù)先的要求。
凡是這樣可擴(kuò)展的結(jié)構(gòu)數(shù)據(jù)解析起來(lái)一定都很困難。
JSON也同樣如此。如果預(yù)先知道JSON結(jié)構(gòu)的情況下,使用JSON進(jìn)行數(shù)據(jù)傳遞簡(jiǎn)直是太美妙了,可以寫出很實(shí)用美觀可讀性強(qiáng)的代碼。如果你是純粹的前臺(tái)開發(fā)人員,一定會(huì)非常喜歡JSON。但是如果你是一個(gè)應(yīng)用開發(fā)人員,就不是那么喜歡了,畢竟xml才是真正的結(jié)構(gòu)化標(biāo)記語(yǔ)言,用于進(jìn)行數(shù)據(jù)傳遞。
而如果不知道JSON的結(jié)構(gòu)而去解析JSON的話,那簡(jiǎn)直是噩夢(mèng)。費(fèi)時(shí)費(fèi)力不說(shuō),代碼也會(huì)變得冗余拖沓,得到的結(jié)果也不盡人意。但是這樣也不影響眾多前臺(tái)開發(fā)人員選擇JSON。因?yàn)閖son.js中的toJSONString()就可以看到JSON的字符串結(jié)構(gòu)。當(dāng)然不是使用這個(gè)字符串,這樣仍舊是噩夢(mèng)。常用JSON的人看到這個(gè)字符串之后,就對(duì)JSON的結(jié)構(gòu)很明了了,就更容易的操作JSON。
以上是在Javascript中僅對(duì)于數(shù)據(jù)傳遞的xml與JSON的解析。在Javascript地盤內(nèi),JSON畢竟是主場(chǎng)作戰(zhàn),其優(yōu)勢(shì)當(dāng)然要遠(yuǎn)遠(yuǎn)優(yōu)越于xml。如果JSON中存儲(chǔ)Javascript復(fù)合對(duì)象,而且不知道其結(jié)構(gòu)的話,我相信很多程序員也一樣是哭著解析JSON的。
◆實(shí)例比較
XML和JSON都使用結(jié)構(gòu)化方法來(lái)標(biāo)記數(shù)據(jù),下面來(lái)做一個(gè)簡(jiǎn)單的比較。
用XML表示中國(guó)部分省市數(shù)據(jù)如下:
<?xml version="1.0" encoding="utf-8"?> <country> <name>中國(guó)</name> <province> <name>黑龍江</name> <cities> <city>哈爾濱</city> <city>大慶</city> </cities> </province> <province> <name>廣東</name> <cities> <city>廣州</city> <city>深圳</city> <city>珠海</city> </cities> </province> </country>
用JSON表示如下:
{ {name:"中國(guó)", province:[ { name:"黑龍江", cities:{ city:["哈爾濱","大慶"] }, {name:"廣東", cities:{ city:["廣州","深圳","珠海"] } }
編碼的可讀性,xml有明顯的優(yōu)勢(shì),畢竟人類的語(yǔ)言更貼近這樣的說(shuō)明結(jié)構(gòu)。json讀起來(lái)更像一個(gè)數(shù)據(jù)塊,讀起來(lái)就比較費(fèi)解了。不過(guò),我們讀起來(lái)費(fèi)解的語(yǔ)言,恰恰是適合機(jī)器閱讀,所以通過(guò)json的索引.province[0].name就能夠讀取“黑龍江”這個(gè)值。
編碼的手寫難度來(lái)說(shuō),xml還是舒服一些,好讀當(dāng)然就好寫。不過(guò)寫出來(lái)的字符JSON就明顯少很多。去掉空白制表以及換行的話,JSON就是密密麻麻的有用數(shù)據(jù),而xml卻包含很多重復(fù)的標(biāo)記字符。
?
JSON在線校驗(yàn)工具
前言
JSON格式取代了xml給網(wǎng)絡(luò)傳輸帶來(lái)了很大的便利,但是卻沒有了xml的一目了然,尤其是json數(shù)據(jù)很長(zhǎng)的時(shí)候,我們會(huì)陷入繁瑣復(fù)雜的數(shù)據(jù)節(jié)點(diǎn)查找中。
但是國(guó)人的一款在線工具 BeJson 給眾多程序員帶來(lái)了一陣涼風(fēng)。
功能簡(jiǎn)介
1. JSON格式化校驗(yàn)
很多人在得到JSON數(shù)據(jù)后,一時(shí)沒有辦法判斷JSON數(shù)據(jù)格式是否正確,是否少或多符號(hào)而導(dǎo)致程序不能解析,這個(gè)功能正好能幫助大家來(lái)完成JSON格式的校驗(yàn)。
2. JSON視圖
想必很多程序員都會(huì)遇到當(dāng)找一個(gè)節(jié)點(diǎn)的時(shí)候,會(huì)發(fā)現(xiàn)如果直接對(duì)著一行行數(shù)據(jù)無(wú)從下手,就算知道哪個(gè)位置,還要一個(gè)節(jié)點(diǎn)一個(gè)節(jié)點(diǎn)的往下找,萬(wàn)一一不留神又得從頭開始找的麻煩事。
有了這個(gè)功能,一切JSON數(shù)據(jù)都會(huì)變成視圖格式,一目了然,什么對(duì)象下有多少數(shù)組,一個(gè)數(shù)組下有多少對(duì)象。
這個(gè)功能非常實(shí)用。不光有視圖功能還有格式化、壓縮、轉(zhuǎn)義、校驗(yàn)功能。總之很強(qiáng)大。
3. 壓縮轉(zhuǎn)義
程序員在寫JSON語(yǔ)句測(cè)試用例的時(shí)候,很多時(shí)候?yàn)榱朔奖阒苯訉懥藗€(gè)JSON字符串做測(cè)試,但是又陷入了無(wú)止境的雙引號(hào)轉(zhuǎn)義的麻煩中。這款功能集壓縮、轉(zhuǎn)義于一身,讓你在寫測(cè)試用例的時(shí)候,如魚得水。
4. JSON在線編輯器
如果你現(xiàn)在的電腦剛巧沒有裝你所熟悉的編輯器,如果你想針對(duì)拿到的JSON數(shù)據(jù)的某個(gè)節(jié)點(diǎn)做數(shù)據(jù)修改時(shí),這個(gè)功能可以滿足你的需求。
5. 在線發(fā)送JSON數(shù)據(jù)
大家都知道,JSON用的最多的還是web項(xiàng)目的開發(fā),那你要測(cè)試一個(gè)接口是否能準(zhǔn)確的接受JSON數(shù)據(jù),那你就得寫一個(gè)頁(yè)面發(fā)送JSON字符串,重復(fù)的做著這件事。隨著這個(gè)功能的橫空出世,你可以擺脫寫測(cè)試頁(yè)面了,因?yàn)檫@個(gè)功能可以將指定的JSON數(shù)據(jù)發(fā)送指定的url,方便吧。
6. JSON著色
很多人在寫文檔時(shí),總希望文檔能一目了然,但是面對(duì)著白底黑字的JSON數(shù)據(jù)總是提不起精神沒關(guān)系,使用這個(gè)功能,所有的關(guān)鍵字都會(huì)被著色,數(shù)據(jù)結(jié)構(gòu)一目了然。
7. JSON-XML互轉(zhuǎn)
顧名思義,將JSON格式的數(shù)據(jù)轉(zhuǎn)化成XML格式、或者XML格式的數(shù)據(jù)轉(zhuǎn)化成JSON格式,一切都不是問題。
更多JSON 數(shù)據(jù)格式相關(guān)文章請(qǐng)關(guān)注PHP中文網(wǎng)!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

JavaScript's garbage collection mechanism automatically manages memory through a tag-clearing algorithm to reduce the risk of memory leakage. The engine traverses and marks the active object from the root object, and unmarked is treated as garbage and cleared. For example, when the object is no longer referenced (such as setting the variable to null), it will be released in the next round of recycling. Common causes of memory leaks include: ① Uncleared timers or event listeners; ② References to external variables in closures; ③ Global variables continue to hold a large amount of data. The V8 engine optimizes recycling efficiency through strategies such as generational recycling, incremental marking, parallel/concurrent recycling, and reduces the main thread blocking time. During development, unnecessary global references should be avoided and object associations should be promptly decorated to improve performance and stability.

There are three common ways to initiate HTTP requests in Node.js: use built-in modules, axios, and node-fetch. 1. Use the built-in http/https module without dependencies, which is suitable for basic scenarios, but requires manual processing of data stitching and error monitoring, such as using https.get() to obtain data or send POST requests through .write(); 2.axios is a third-party library based on Promise. It has concise syntax and powerful functions, supports async/await, automatic JSON conversion, interceptor, etc. It is recommended to simplify asynchronous request operations; 3.node-fetch provides a style similar to browser fetch, based on Promise and simple syntax

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

Which JavaScript framework is the best choice? The answer is to choose the most suitable one according to your needs. 1.React is flexible and free, suitable for medium and large projects that require high customization and team architecture capabilities; 2. Angular provides complete solutions, suitable for enterprise-level applications and long-term maintenance; 3. Vue is easy to use, suitable for small and medium-sized projects or rapid development. In addition, whether there is an existing technology stack, team size, project life cycle and whether SSR is needed are also important factors in choosing a framework. In short, there is no absolutely the best framework, the best choice is the one that suits your needs.

Hello, JavaScript developers! Welcome to this week's JavaScript news! This week we will focus on: Oracle's trademark dispute with Deno, new JavaScript time objects are supported by browsers, Google Chrome updates, and some powerful developer tools. Let's get started! Oracle's trademark dispute with Deno Oracle's attempt to register a "JavaScript" trademark has caused controversy. Ryan Dahl, the creator of Node.js and Deno, has filed a petition to cancel the trademark, and he believes that JavaScript is an open standard and should not be used by Oracle

IIFE (ImmediatelyInvokedFunctionExpression) is a function expression executed immediately after definition, used to isolate variables and avoid contaminating global scope. It is called by wrapping the function in parentheses to make it an expression and a pair of brackets immediately followed by it, such as (function(){/code/})();. Its core uses include: 1. Avoid variable conflicts and prevent duplication of naming between multiple scripts; 2. Create a private scope to make the internal variables invisible; 3. Modular code to facilitate initialization without exposing too many variables. Common writing methods include versions passed with parameters and versions of ES6 arrow function, but note that expressions and ties must be used.

Promise is the core mechanism for handling asynchronous operations in JavaScript. Understanding chain calls, error handling and combiners is the key to mastering their applications. 1. The chain call returns a new Promise through .then() to realize asynchronous process concatenation. Each .then() receives the previous result and can return a value or a Promise; 2. Error handling should use .catch() to catch exceptions to avoid silent failures, and can return the default value in catch to continue the process; 3. Combinators such as Promise.all() (successfully successful only after all success), Promise.race() (the first completion is returned) and Promise.allSettled() (waiting for all completions)

CacheAPI is a tool provided by the browser to cache network requests, which is often used in conjunction with ServiceWorker to improve website performance and offline experience. 1. It allows developers to manually store resources such as scripts, style sheets, pictures, etc.; 2. It can match cache responses according to requests; 3. It supports deleting specific caches or clearing the entire cache; 4. It can implement cache priority or network priority strategies through ServiceWorker listening to fetch events; 5. It is often used for offline support, speed up repeated access speed, preloading key resources and background update content; 6. When using it, you need to pay attention to cache version control, storage restrictions and the difference from HTTP caching mechanism.
