Home Web Front-end JS Tutorial Convert Json objects and strings to each other. Detailed introduction to json data splicing and JSON usage.

Convert Json objects and strings to each other. Detailed introduction to json data splicing and JSON usage.

Dec 09, 2016 am 10:03 AM
json

JSON (JavaScript Object Notation) is a lightweight data exchange format. It is based on a subset of ECMAScript. JSON uses a completely language-independent text format, but also uses conventions similar to the C language family (including C, C++, C#, Java, JavaScript, Perl, Python, etc.). These properties make JSON an ideal data exchange language. It is easy for humans to read and write, and it is also easy for machines to parse and generate (generally used to increase network transmission rates).

1. Convert JSON string to JSON object: eval() and JSON.parse

eg- json string:

var data = '{ "name": "dran", "sex": "man" }';
var obj = eval("("+data+")"); 或者
var obj = JSON.parse(data);
Copy after login

Then, you can read it like this: alert(obj.name + obj. sex);

Tips: Why do you need to add ("("+data+")"); to eval?

The reason lies in: the problem of eval itself. Since json starts and ends with "{}", it will be processed as a statement block in JS, so it must be forced to be converted into an expression.

The purpose of adding parentheses is to force the eval function to convert the expression in the parentheses into an object when processing JavaScript code, rather than executing it as a statement. For example, if the object literal {} is not added with outer brackets, then eval will recognize the braces as the start and end marks of the JavaScript code block, and {} will be considered to execute an empty statement

2. Convert JSON object to JSON string: obj.toJSONString() or global method JSON.stringify(obj) (obj represents json object)

eg-json对象: var obj = { "name": "dran", "sex": "man" };
var jstring = JSON.stringify(obj) ;// 建议用这个
var jstring = obj.toJSONString(); //toJSONString()不是js原生的方法,需要引入相应的库或自己定义后才能用 (不习惯用)
Copy after login

Then, you can read it like this: alert(jstring );

Note:

Currently, Firefox, Opera, IE8 and above also provide local JSON support. Among them, the functions provided by the JSON interpreter are: JSON.parse, JSON.stringify. For browsers that do not provide native JSON support, the script json2.js can be introduced to implement the JSON conversion function. The json2.js script can be downloaded from https://github.com/douglascrockford/JSON-js/blob/master/json2.js

When AJAX implements front-end and back-end data interaction, the JSON data format is usually used. For JSON, there are strict code specifications. Once there is a problem with the format, the corresponding effect cannot be displayed, and an error is not reported on the console.

Additional: ajax reads json data and splicing displays:

json file:

{
"first":[
{"name":"张三","sex":"男","like":["吃饭","睡觉","打豆豆"]},
{"name":"李四","sex":"男"},
{"name":"王武","sex":"男"},
{"name":"李梅","sex":"女"},
],
"second":[
{"name":"上海大学","area":"上海"},
{"name":"武汉大学","area":"武汉"},
{"name":"北京大学","area":"北京"},
{"name":"山东大学","area":"山东"},
]
}
Copy after login

html and ajax code

1. Use for loop

$.ajax({
url : "ceshi.json",
type : "POST",
dataType :"text", //浏览器把json文件当作文本文件 不然读取不出来 权宜之策就改成了text, 因为测试, json文件格式正确书写
success: function(data) {
var dataJson = eval("("+data+")"); // 将json字符串数据解析成对象
var arr1 = dataJson.first;
var arr2 = dataJson.second;
//一栏显示 用for循环完成数组解析
for(var i = 0; i<arr1.length; i++){
for(var j = 0; j<arr2.length; j++){
var str=&#39;<div style="display:block">&#39;+
&#39;<div>姓名:&#39;+arr1[i].name+&#39; 性别:&#39;+arr1[i].sex+&#39;</div>&#39;+
&#39;<div>学校:&#39;+arr2[j].name+&#39;</div>&#39;+
&#39;<div>地点:&#39;+arr2[j].area+&#39;</div>&#39;+
//&#39;<div>喜好:&#39;+arr1[i].like+&#39;</div>&#39;+ //全显示
//&#39;<div>喜好:&#39;+arr1[i].like[1]+&#39;</div>&#39;+ //单独设置
//&#39;<div>喜好:&#39;+arr1[i].like[0]+&#39;</div>&#39;+
&#39;</div>&#39;;
}
$(".result").append(str);
}
//分层显示
//var str = "";
// var str1 = "";
// if (arr1 != null) {
// for (var i = 0; i < arr1.length; i++) { //这里面都是创建并赋值
// str += "<span>" + arr1[i].name + "</span><span>" + arr1[i].sex + "</span><br>";
// }
// $(".result").html(str);
// }
// if (arr2 != null) {
// for (var j = 0; j < arr2.length; j++) {
// str1 += "<span>" + arr2[j].name + "</span><span>" + arr2[j].area+ "</span><br>";
// }
// $(".result2").html(str1);
// }
},
error:function(data){
alert("error");
}
})
<div class="result">frist:</div>
<div class="result2">second:</div>
for
Copy after login

2. Each loop uses $.each method to traverse the returned data date and insert it into class .result

JSON:

[
{"name":"张三","sex":"男","like":["吃饭","睡觉","打豆豆"]},
{"name":"李四","sex":"男"},
{"name":"王武","sex":"男"},
{"name":"李梅","sex":"女"},
]
$.ajax({
url : "ceshi.json",
type : "POST",
dataType :"text", //浏览器把json文件当作文本文件 不然读取不出来 权宜之策就改成了text, 因为测试, json文件格式正确书写
success: function(data) {
var dataJson = eval("("+data+")"); // 将json字符串数据解析成对象
//each循环 使用$.each方法遍历返回的数据date,插入到class为 .result中 i 表示索引 item 信息值 对象
$.each(dataJson,function(i,item){
var str=&#39;<div style="display:block">&#39;+
&#39;<div>姓名:&#39;+item.name+&#39; 性别:&#39;+item.sex+&#39;</div>&#39;+
&#39;<div>like:&#39;+item.like+&#39;</div>&#39;+
&#39;</div>&#39;;
$(".result").append(str);
})
},
error:function(data){
alert("error");
}
})
<div class="result"></div>
each
Copy after login

PS: For general js to generate json objects, you only need to replace the $.each() method with a for statement, and the others remain unchanged

JSON data usage method:

//json对象:
var jsonObj= {
"name":" 张三",
"sex":"男",
"age":26,
};
使用: jsonObj.name= "张三"
jsonObj.age= "26"
//json数组: []下标 从 0 开始
var jsonArr =[
{"name":"张三","sex":"男","like":["吃饭","睡觉","打豆豆"]},
{"name":"李四","sex":"男"},
{"name":"王武","sex":"男"},
]
使用: jsonArr[0].sex="男"
jsonArr[1].name="李四"
//多个数组: []下标 从 0 开始
var options = {
"city" :[
{
"name":"上海",
"area":"普陀区",
"option":"真北路",
"correct":"1"
},
{
"name":"石家庄",
"area":"河北",
"option":"在北方",
"correct":"2"
}],
"world":[
{
"title":"美国",
"content":"好莱坞大片 科幻"
},
{
"title":"中国",
"content":"爱我中华,虽远必诛"
}
]
};
options.city[0].area="普陀区"
options.world[1].content="爱我中华,虽远必诛
Copy after login


Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Combination of golang WebSocket and JSON: realizing data transmission and parsing Combination of golang WebSocket and JSON: realizing data transmission and parsing Dec 17, 2023 pm 03:06 PM

The combination of golangWebSocket and JSON: realizing data transmission and parsing In modern Web development, real-time data transmission is becoming more and more important. WebSocket is a protocol used to achieve two-way communication. Unlike the traditional HTTP request-response model, WebSocket allows the server to actively push data to the client. JSON (JavaScriptObjectNotation) is a lightweight format for data exchange that is concise and easy to read.

How to exclude a field from JSON using @Expose annotation in Java? How to exclude a field from JSON using @Expose annotation in Java? Sep 16, 2023 pm 09:49 PM

The Gson@Expose annotation can be used to mark whether a field is exposed (contained or not) for serialization or deserialization. The @Expose annotation can take two parameters, each parameter is a boolean value and can take the value true or false. In order for GSON to react to the @Expose annotation, we have to create a Gson instance using the GsonBuilder class and need to call the excludeFieldsWithoutExposeAnnotation() method, which configures Gson to exclude all fields without Expose annotation from serialization or deserialization. Syntax publicGsonBuilderexclud

What is the difference between MySQL5.7 and MySQL8.0? What is the difference between MySQL5.7 and MySQL8.0? Feb 19, 2024 am 11:21 AM

MySQL5.7 and MySQL8.0 are two different MySQL database versions. There are some main differences between them: Performance improvements: MySQL8.0 has some performance improvements compared to MySQL5.7. These include better query optimizers, more efficient query execution plan generation, better indexing algorithms and parallel queries, etc. These improvements can improve query performance and overall system performance. JSON support: MySQL 8.0 introduces native support for JSON data type, including storage, query and indexing of JSON data. This makes processing and manipulating JSON data in MySQL more convenient and efficient. Transaction features: MySQL8.0 introduces some new transaction features, such as atomic

Performance optimization tips for converting PHP arrays to JSON Performance optimization tips for converting PHP arrays to JSON May 04, 2024 pm 06:15 PM

Performance optimization methods for converting PHP arrays to JSON include: using JSON extensions and the json_encode() function; adding the JSON_UNESCAPED_UNICODE option to avoid character escaping; using buffers to improve loop encoding performance; caching JSON encoding results; and considering using a third-party JSON encoding library.

Use the json.MarshalIndent function in golang to convert the structure into a formatted JSON string Use the json.MarshalIndent function in golang to convert the structure into a formatted JSON string Nov 18, 2023 pm 01:59 PM

Use the json.MarshalIndent function in golang to convert the structure into a formatted JSON string. When writing programs in Golang, we often need to convert the structure into a JSON string. In this process, the json.MarshalIndent function can help us. Implement formatted output. Below we will explain in detail how to use this function and provide specific code examples. First, let's create a structure containing some data. The following is an indication

How to handle XML and JSON data formats in C# development How to handle XML and JSON data formats in C# development Oct 09, 2023 pm 06:15 PM

How to handle XML and JSON data formats in C# development requires specific code examples. In modern software development, XML and JSON are two widely used data formats. XML (Extensible Markup Language) is a markup language used to store and transmit data, while JSON (JavaScript Object Notation) is a lightweight data exchange format. In C# development, we often need to process and operate XML and JSON data. This article will focus on how to use C# to process these two data formats, and attach

Pandas usage tutorial: Quick start for reading JSON files Pandas usage tutorial: Quick start for reading JSON files Jan 13, 2024 am 10:15 AM

Quick Start: Pandas method of reading JSON files, specific code examples are required Introduction: In the field of data analysis and data science, Pandas is one of the important Python libraries. It provides rich functions and flexible data structures, and can easily process and analyze various data. In practical applications, we often encounter situations where we need to read JSON files. This article will introduce how to use Pandas to read JSON files, and attach specific code examples. 1. Installation of Pandas

How do annotations in the Jackson library control JSON serialization and deserialization? How do annotations in the Jackson library control JSON serialization and deserialization? May 06, 2024 pm 10:09 PM

Annotations in the Jackson library control JSON serialization and deserialization: Serialization: @JsonIgnore: Ignore the property @JsonProperty: Specify the name @JsonGetter: Use the get method @JsonSetter: Use the set method Deserialization: @JsonIgnoreProperties: Ignore the property @ JsonProperty: Specify name @JsonCreator: Use constructor @JsonDeserialize: Custom logic

See all articles