search
HomeWeb Front-endJS TutorialAn article to let you know in detail what JSON is

JSON detailed explanation:

The full name of JSON is "JavaScript Object Notation", which means JavaScript object notation. It is a text-based, language-independent, lightweight data exchange format. XML is also a data exchange format. Why wasn't XML chosen? Although XML can be used as a cross-platform data exchange format, it is very inconvenient to process XML in JS (abbreviation for JavaScript). At the same time, there are more XML tags than data, which increases the traffic generated by the exchange, while JSON does not have any tags attached. JS can be processed as objects, so we prefer JSON to exchange data. This article mainly explains JSON from the following aspects.

1, Two structures of JSON
2, Understanding JSON strings
3, How to use JSON in JS
4, How to use JSON in .NET
5, Summary

1. Two structures of JSON

JSON has two representation structures, objects and arrays.
The object structure starts with "{" braces and ends with "}" braces. The middle part consists of 0 or more "key (keyword)/value (value)" pairs separated by ",". Keywords and values ​​are separated by ":", and the syntax structure is like code.

{
    key1:value1,
    key2:value2,
    ...
}

The keyword is a string, and the value can be a string, a numerical value, true, false, null, an object or an array

The array structure starts with "[" and ends with "]" . The middle consists of 0 or more value lists separated by ",", and the syntax structure is like code.

[
    {
        key1:value1,
        key2:value2 
    },
    {
         key3:value3,
         key4:value4   
    }
]

2. Understanding JSON strings

#I have always been confused before, and I can’t distinguish between ordinary strings and json characters The difference between string and json object. After some research I finally figured it out. For example, in js.

String: This is easy to explain. It refers to characters enclosed by "" double quotes or '' single quotes. For example: var comStr = 'this is string';
json string: refers to a js string that meets the json format requirements. For example: var jsonStr = "{StudentID:'100',Name:'tmac',Hometown:'usa'}";
json object: refers to a js object that meets the json format requirements. For example: var jsonObj = { StudentID: "100", Name: "tmac", Hometown: "usa" };

3. How to use JSON in JS

JSON is a subset of JS, so you can easily read and write JSON in JS. There are two methods for reading and writing JSON, namely using the "." operator and the "[key]" method.
We first define a JSON object, the code is as follows.

var obj = {
            1: "value1",
            "2": "value2",
            count: 3,
            person: [ //数组结构JSON对象,可以嵌套使用
                        {
                            id: 1,
                            name: "张三"
                        },
                        {
                            id: 2,
                            name: "李四"
                        }
                   ],
            object: { //对象结构JSON对象
                id: 1,
                msg: "对象里的对象"    
            }
        };

1. Read data from JSON

function ReadJSON() {
            alert(obj.1); //会报语法错误,可以用alert(obj["1"]);说明数字最好不要做关键字
            alert(obj.2); //同上

            alert(obj.person[0].name); //或者alert(obj.person[0]["name"])
            alert(obj.object.msg); //或者alert(obj.object["msg"])
        }

2. Write data to JSON

For example, if you want to add a piece of data to JSON, the code As shown below:

function Add() { 
            //往JSON对象中增加了一条记录
            obj.sex= "男" //或者obj["sex"]="男"
        }

The JSON object after adding data is as follows:

An article to let you know in detail what JSON is

3. Modify the data in JSON

We Now we need to modify the value of count in JSON. The code is as follows:

function Update() {
           obj.count = 10; //或obj["count"]=10
       }

The modified JSON is as shown in the figure:

An article to let you know in detail what JSON is

4. Delete the Data

We now delete the count data from JSON. The code is as follows:

function Delete() {            
    delete obj.count;//或obj["count"]
}

The deleted JSON is as shown in the figure:

An article to let you know in detail what JSON is

You can see that count has been deleted from the JSON object.

5. Convenience JSON object

You can use the for...in...loop to traverse the data in the JSON object. For example, if we want to traverse the value of the output obj object, the code is as follows:

function Traversal() {
            for (var c in obj) {
                console.log(c + ":", obj[c]);
            }
}

The program output result is:

An article to let you know in detail what JSON is

##4. How to use JSON# in .NET ##When it comes to using JSON in .net, we have to mention JSON.NET. It is a very famous tool for processing JSON in .net. The following two functions are most commonly used.

1. Convert .NET objects into JSON strings through serialization

In the web development process, we often need to query data from the database (usually a set, list or array, etc.) into a JSON format string and send it back to the client, which requires serialization. The

SerializeObject

method of the JsonConvert object is used here. The syntax format is:

JsonConvert

.SerializeObject(object)The "object" in the code is the sequence .NET object, the json string returned after serialization.

For example, now we have a TStudent student table. The fields and existing data in the table are as shown in the figure

An article to let you know in detail what JSON is

从表中我们可以看到一共有五条数据,现在我们要从数据库中取出这些数据,然后利用JSON.NET的JsonConvert对象序列化它们为json字符串,并显示在页面上。C#代码如下

protected void Page_Load(object sender, EventArgs e)
        {            using (L2SDBDataContext db = new L2SDBDataContext())
            {
                List<Student> studentList = new List<Student>();                var query = from s in db.TStudents                            select new { 
                                StudentID=s.StudentID,
                                Name=s.Name,
                                Hometown=s.Hometown,
                                Gender=s.Gender,
                                Brithday=s.Birthday,
                                ClassID=s.ClassID,
                                Weight=s.Weight,
                                Height=s.Height,
                                Desc=s.Desc
                            };                foreach (var item in query)
                {
                    Student student = new Student { StudentID=item.StudentID,Name=item.Name,Hometown=item.Hometown,Gender=item.Gender,Brithday=item.Brithday,ClassID=item.ClassID,Weight=item.Weight,Height=item.Height,Desc=item.Desc};
                    studentList.Add(student);
                }
                lbMsg.InnerText = JsonConvert.SerializeObject(studentList);
            }
        }

输出结果为:

An article to let you know in detail what JSON is

从图中我们可以看到,数据库中的5条记录全部取出来并转化为json字符串了。

2,使用LINQ to JSON定制JSON数据

使用JsonConvert对象的SerializeObject只是简单地将一个list或集合转换为json字符串。但是,有的时候我们的前端框架比如ExtJs对服务端返回的数据格式是有一定要求的,比如下面的数据格式,这时就需要用到JSON.NETLINQ to JSON,LINQ to JSON的作用就是根据需要的格式来定制json数据。

比如经常用在分页的json格式如代码:

{ 
    "total": 5, //记录总数
    "rows":[
        //json格式的数据列表
    ]
}

使用LINQ to JSON前,需要引用Newtonsoft.Jsondllusing Newtonsoft.Json.Linq的命名空间。LINQ to JSON主要使用到JObject, JArray, JProperty和JValue这四个对象,JObject用来生成一个JSON对象,简单来说就是生成”{}”,JArray用来生成一个JSON数组,也就是”[]”,JProperty用来生成一个JSON数据,格式为key/value的值,而JValue则直接生成一个JSON值。下面我们就用LINQ to JSON返回上面分页格式的数据。代码如下:

protected void Page_Load(object sender, EventArgs e)
        {
            using (L2SDBDataContext db = new L2SDBDataContext())
            {
                //从数据库中取出数据并放到列表list中
                List<Student> studentList = new List<Student>();
                var query = from s in db.TStudents
                            select new
                            {
                                StudentID = s.StudentID,
                                Name = s.Name,
                                Hometown = s.Hometown,
                                Gender = s.Gender,
                                Brithday = s.Birthday,
                                ClassID = s.ClassID,
                                Weight = s.Weight,
                                Height = s.Height,
                                Desc = s.Desc
                            };
                foreach (var item in query)
                {
                    Student student = new Student { StudentID = item.StudentID, Name = item.Name, Hometown = item.Hometown, Gender = item.Gender, Brithday = item.Brithday, ClassID = item.ClassID, Weight = item.Weight, Height = item.Height, Desc = item.Desc };
                    studentList.Add(student);
                }

                //基于创建的list使用LINQ to JSON创建期望格式的JSON数据
                lbMsg.InnerText = new JObject(
                        new JProperty("total",studentList.Count),
                        new JProperty("rows",
                                new JArray(
                                        //使用LINQ to JSON可直接在select语句中生成JSON数据对象,无须其它转换过程
                                        from p in studentList
                                        select new JObject(
                                                new JProperty("studentID",p.StudentID),
                                                new JProperty("name",p.Name),
                                                new JProperty("homeTown",p.Hometown)
                                            )
                                    )
                            )
                    ).ToString();
            }
        }

输出结果为:

An article to let you know in detail what JSON is

3、处理客户端提交的客户端数据

客户端提交过来的数据一般都是json字符串,有了更好地进行操作(面向对象的方式),所以我们一般都会想办法将json字符串转换为json对象。例如客户端提交了以下数组格式json字符串。

[
    {StudentID:"100",Name:"aaa",Hometown:"china"},
    {StudentID:"101",Name:"bbb",Hometown:"us"},
    {StudentID:"102",Name:"ccc",Hometown:"england"}
]

在服务端就可以使用JObject或JArray的Parse方法轻松地将json字符串转换为json对象,然后通过对象的方式提取数据。下面是服务端代码。

protected void Page_Load(object sender, EventArgs e)
        {
            string inputJsonString = @"
                [
                    {StudentID:&#39;100&#39;,Name:&#39;aaa&#39;,Hometown:&#39;china&#39;},
                    {StudentID:&#39;101&#39;,Name:&#39;bbb&#39;,Hometown:&#39;us&#39;},
                    {StudentID:&#39;102&#39;,Name:&#39;ccc&#39;,Hometown:&#39;england&#39;}
                ]";
            JArray jsonObj = JArray.Parse(inputJsonString);
            string message = @"<table border=&#39;1&#39;>
                    <tr><td width=&#39;80&#39;>StudentID</td><td width=&#39;100&#39;>Name</td><td width=&#39;100&#39;>Hometown</td></tr>";
            string tpl = "<tr><td>{0}</td><td>{1}</td><td>{2}</td></tr>";
            foreach (JObject jObject in jsonObj)
            {
                message += String.Format(tpl, jObject["StudentID"], jObject["Name"],jObject["Hometown"]);
            }
            message += "</table>";
            lbMsg.InnerHtml = message;
        }

输出结果为:

An article to let you know in detail what JSON is

当然,服务端除了使用LINQ to JSON来转换json字符串外,也可以使用JsonConvertDeserializeObject方法。如下面代码实现上面同样的功能。

List<Student> studentList = JsonConvert.DeserializeObject<List<Student>>(inputJsonString);//注意这里必须为List<Student>类型,因为客户端提交的是一个数组json
            foreach (Student student in studentList)
            {
                message += String.Format(tpl, student.StudentID, student.Name,student.Hometown);
            }

总结:

在客户端,读写json对象可以使用”.”操作符或”["key”]”,json字符串转换为json对象使用eval()函数。
在服务端,由.net对象转换json字符串优先使用JsonConvert对象的SerializeObject方法,定制输出json字符串使用LINQ to JSON。由json字符串转换为.net对象优先使用JsonConvert对象的DeserializeObject方法,然后也可以使用LINQ to JSON。

想了解更多相关内容请访问PHP中文网:JSON视频教程

The above is the detailed content of An article to let you know in detail what JSON is. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

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 Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools