Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the basic knowledge points of JSON

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "what are the basic knowledge points of JSON". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what are the basic knowledge points of JSON".

JSON is the abbreviation of JavaScript Object Notation, which means "JavaScript object representation" in Chinese. It is a text format for data exchange, not a programming language. JSON is a lightweight data exchange format based on a subset of ECMAScript (the js specification developed by W3C) and uses a text format that is completely independent of the programming language to store and represent data.

Two structures of JSON

JSON has two representation structures, objects and arrays. The object structure begins with "{" curly braces and ends with "}" braces. The middle part consists of 0 or more pairs of "key (keyword) / value (value)" separated by ",", separated by ":" between keywords and values, and syntax structures such as code.

{key1:value1, key2:value2, … } where the keyword is a string and the value can be a string, numeric value, true,false,null, object, or array

The array structure begins with "[" and ends with "]". The middle consists of 0 or more lists of values separated by ",", with syntax structures such as code.

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

I've always been confused about the difference between normal strings, json strings and json objects. After some research, it was finally figured out. For example, in js.

String: this is easy to explain and refers to the characters included in "" double quotation marks or''single quotation marks. For example: var comStr = 'this is string'; json string: refers to a js string that meets the requirements of the json format. For example: var jsonStr = "{StudentID:'100',Name:'tmac',Hometown:'usa'}"; json object: a js object that meets the requirements of the json format. For example: var jsonObj = {StudentID: "100", Name: "tmac", Hometown: "usa"}

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 ways to read and write JSON, one is to use "." Operator and "[key]". Let's first define a JSON object with the following code.

Var obj = {1: "value1", "2": "value2", count: 3, person: [/ / Array structure JSON object Can be nested to use {id: 1, name: "Zhang San"}, {id: 2 Name: "Li Si"}], object: {/ / object structure JSON object id: 1, msg: "object in object"}}

1. Read data from JSON

Function ReadJSON () {alert (obj.1); / can report syntax errors and can use alert (obj ["1"]); explain that numbers are best not to be the keyword alert (obj.2); / / ditto alert (obj.person [0] .name); / or alert (obj.person [0] ["name"]) alert (obj.object.msg) / / or alert (obj.object ["msg"])}

2. Write data to JSON

For example, to add a piece of data to JSON, the code is as follows:

Function Add () {/ / added an entry to the JSON object to record obj.sex= "male" / / or obj ["sex"] = "male"}. The JSON object after adding data is shown in the figure:

3. Modify the data in JSON

We are now going to modify the value of count in JSON, as follows:

Function Update () {obj.count = 10; / / or obj ["count"] = 10}

The modified JSON is shown in the figure.

4. Delete the data in JSON

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

Function Delete () {delete obj.count;}

The deleted JSON is shown in the figure

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

5, traversing the JSON object

You can use for... In... Loop through the data in the JSON object, for example, we want to iterate over the value of the output obj object, as follows:

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

The output of the program is as follows:

How to use JSON in .NET

When it comes to using JSON in. Net, we have to mention JSON.NET, which is a very famous tool for dealing with JSON in. Net. The following two functions are most commonly used.

1, converting .net objects to JSON strings by serialization

In the process of web development, we often need to convert the data queried from the database (usually a collection, list or array, etc.) into JSON format strings back to the client, which requires serialization. Here we use the SerializeObject method of the JsonConvert object. Its syntax format is: JsonConvert.SerializeObject (object), the "object" in the code is the. Net object to be serialized, and the serialized return is the json string.

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

We can see from the table that there are a total of five pieces of data, and now we need to extract the data from the database and serialize them into json strings using JSON.NET 's JsonConvert object and display them on the page. The C # code is as follows

Protected void Page_Load (object sender, EventArgs e) {using (L2SDBDataContext db = new L2SDBDataContext ()) {List studentList = new List () 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);}}

Output result

From the figure, we can see that all five records in the database have been taken out and converted into json strings.

2. Use LINQ to JSON to customize JSON data

Using the SerializeObject of the JsonConvert object simply converts a list or collection to a json string. However, sometimes our front-end framework, such as ExtJs, has certain requirements for the data format returned by the server, such as the following data format, then we need to use JSON.NET 's LINQ to JSON,LINQ to JSON to customize json data according to the desired format.

For example, json formats that are often used in paging, such as code:

{"total": 5, / / Total number of records "rows": [/ / data list in json format]}

Before using LINQ to JSON, you need to reference the dll of Newtonsoft.Json and the namespace of using Newtonsoft.Json.Linq. LINQ to JSON mainly uses JObject, JArray, JProperty and JValue these four objects, JObject is used to generate a JSON object, simply to generate "{}", JArray is used to generate a JSON array, that is, "[]", JProperty is used to generate a JSON data, the format is key/value value, and JValue directly generates a JSON value. Next we will use LINQ to JSON to return the data in the above paged format. The code is as follows:

Protected void Page_Load (object sender, EventArgs e) {using (L2SDBDataContext db = new L2SDBDataContext ()) {/ / fetch the data from the database and put it in the list list List studentList = new List () 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) } / / create JSON data in the desired format using LINQ to JSON based on the created list lbMsg.InnerText = new JObject (new JProperty ("total", studentList.Count), new JProperty ("rows") New JArray (/ / use LINQ to JSON to generate JSON data objects directly in select statements No other conversion processes from p in studentList select new JObject (new JProperty ("studentID", p.StudentID), new JProperty ("name", p.Name) New JProperty ("homeTown", p.Hometown)) .ToString () }}

The output is as follows:

3. Handle the JSON data submitted by the client

The data submitted by the client is generally a json string, so we will generally find a way to convert the json string to a json object because of the better operation (object-oriented way). For example, the client submitted the following array format json string.

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

On the server side, you can easily convert a json string into a json object using the Parse method of JObject or JArray, and then extract the data as an object. Here is the server code.

Protected void Page_Load (object sender, EventArgs e) {string inputJsonString = @ "[{StudentID:'100',Name:'aaa',Hometown:'china'}, {StudentID:'101',Name:'bbb',Hometown:'us'}, {StudentID:'102',Name:'ccc'] Hometown:'england'}] " JArray jsonObj = JArray.Parse (inputJsonString); string message = @ "

"; string tpl =

"; foreach (JObject jObject in jsonObj) {message + = String.Format (tpl, jObject [" StudentID "], jObject [" Name "], jObject [" Hometown "]);} message + ="

StudentIDNameHometown {0} {1} {2}

"; lbMsg.InnerHtml = message;}

Output result:

Of course, in addition to using LINQ to JSON to convert json strings, the server can also use JsonConvert's DeserializeObject method. The following code implements the same function as above.

List studentList = JsonConvert.DeserializeObject (inputJsonString); / / Note that this must be of type List, because the client submits an array of jsonforeach (Student student in studentList) {message + = String.Format (tpl, student.StudentID, student.Name,student.Hometown). } Thank you for your reading. The above is the content of "what are the basic knowledge points of JSON". After the study of this article, I believe you have a deeper understanding of what are the basic knowledge points of JSON, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report