search
HomeWeb Front-endJS TutorialIn-depth Understanding of JavaScript Series (9) There is no such thing as a 'JSON object'! _javascript skills

Preface
The purpose of writing this article is that I often see developers saying: convert strings into JSON objects, convert JSON objects into strings and other similar topics, so I compiled and translated an article by a foreigner that I had collected previously. Here it is for everyone to discuss. If there are any mistakes, please point them out. Thank you.

Text
The topic of this article is written based on ECMAScript262-3. The new 262-5 specification in 2011 added JSON objects, which is related to what we usually call JSON, but it is not the same thing. , the last section of the article will talk about the newly added JSON object.

Original English text: http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/
I would like to clarify a very common Misunderstanding, I think many JavaScript developers mistakenly call JavaScript object literals (JSON Objects) because its syntax is the same as described in the JSON specification, but the specification also clearly states JSON is just a data exchange language, it is only called JSON when we use it in a string context.

Serialization and Deserialization
When two programs (or servers, languages, etc.) need to communicate interactively, they tend to use string strings because strings are parsed in similar ways in many languages. Complex data structures are often used, and are composed of various square brackets {}, parentheses (), brackets and spaces. This string is just a string of characters that are standardized as required.

To this end, we have developed standard rules and syntax for describing these complex data structures as a string. JSON is just one of the syntaxes. It can describe objects, arrays, strings, numbers, booleans, and null in a string context, and then transmit them between programs and deserialize them into the required format. YAML and XML (even request params) are also popular data exchange formats, but, we like JSON, who call us JavaScript developers!

Literals
Quoting a few sentences from the Mozilla Developer Center for your reference:

They are fixed values, not variables, allowing you to understand the script "literally". (Literals)
String literals are composed of zero or more characters surrounded by double quotes (") or single quotes ('). (Strings Literals)
Object literals are composed of curly braces ( {}) zero or more object property name-value pairs (Object Literals)
When is it JSON and when is it not JSON?
JSON is designed to describe a data exchange format. It also has its own syntax, which is a subset of JavaScript.
{ "prop": "val" } Such a declaration may be a JavaScript object literal or a JSON string, depending on the context in which it is used. If it is used in a string context (enclosed in single or double quotes, or read from a text file), it is a JSON string. If it is used in an object literal context, it is an object literal <.>

Copy code The code is as follows:
// This is a JSON string
var foo = '{ "prop": "val" }';

// This is an object literal
var bar = { "prop": "val" };

And please note that JSON has a very strict syntax. In the string context { "prop": "val" } is a legal JSON, but { prop: "val" } and { 'prop': 'val' } are indeed illegal. All attribute names and their values ​​must be enclosed in double quotes. Single quotes are not allowed. In addition, even if you use escaped single quotes, you can check here for detailed syntax rules. >
Put it in context
People may scoff: Isn’t JavaScript code a big string?

Of course it is, all JavaScript code and HTML (maybe other things) They are all strings until the browser parses them. At this time, the .jf file or inline JavaScript code is no longer a string, but is regarded as the real JavaScript source code, just like innterHTML in the page. It is not a string, but is parsed into a DOM structure.

Again, it depends on the context. If you use a JavaScript object with curly brackets in the string context, it is a JSON string. And if used in the context of object literals, it is an object literal.

Real JSON object
As mentioned at the beginning, object literals are not JSON objects, but there are real JSON objects. But the two are completely different concepts. In the new version of the browser, JSON objects have been converted into native built-in objects. There are currently two static methods: JSON.parse is used to deserialize JSON strings into objects, and JSON.stringify is used to deserialize JSON strings into objects. Serialize the object into a JSON string. Older versions of browsers do not support this object, but you can achieve the same functionality through json2.js.

If you still don’t understand, don’t worry, just refer to the example:


Copy the code The code is as follows :

// This is a JSON string, such as getting string information from AJAX
var my_json_string = '{ "prop": "val" }';

// Convert the string Deserialize into object
var my_obj = JSON.parse( my_json_string );

alert( my_obj.prop == 'val' ); // Prompt is true, just as expected!

// Serialize the object into a JSON string
var my_other_json_string = JSON.stringify( my_obj );

In addition, Paul Irish mentioned that Douglas Crockford used "JSON object" in the JSON RFC , but in that context, he means "object described as JSON string" not "object literal".

More information
If you want to know more about JSON, the following link will definitely be useful to you:

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.