


Detailed explanation of the steps to convert Json objects and strings to each other
This time I will bring you a detailed explanation of the steps for converting Json objects and strings. What are the precautions for converting Json objects and strings? The following is a practical case, let's take a look.
JSON(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);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原生的方法,需要引入相应的库或自己定义后才能用 (不习惯用)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 the
https://github.com/douglascrockford/JSON-js/blob/master/json2.js page
When AJAX implements front-end and back-end data interaction , usually using the JSON data format. For JSON, there are strictcode specifications. Once there is a problem with the format, the corresponding effect cannot be displayed, and an error is not reported on the console
Supplement: ajax reads json data splicing display:
json file:{ "first":[ {"name":"张三","sex":"男","like":["吃饭","睡觉","打豆豆"]}, {"name":"李四","sex":"男"}, {"name":"王武","sex":"男"}, {"name":"李梅","sex":"女"}, ], "second":[ {"name":"上海大学","area":"上海"}, {"name":"武汉大学","area":"武汉"}, {"name":"北京大学","area":"北京"}, {"name":"山东大学","area":"山东"}, ] }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 for var>'+ '<p>姓名:'+arr1[i].name+' 性别:'+arr1[i].sex+'</p>'+ '<p>学校:'+arr2[j].name+'</p>'+ '<p>地点:'+arr2[j].area+'</p>'+ //'<p>喜好:'+arr1[i].like+'</p>'+ //全显示 //'<p>喜好:'+arr1[i].like[1]+'</p>'+ //单独设置 //'<p>喜好:'+arr1[i].like[0]+'</p>'+ ''; } $(".result").append(str); } //分层显示 //var str = ""; // var str1 = ""; // if (arr1 != null) { // for (var i = 0; i " + arr1[i].name + "<span>" + arr1[i].sex + "</span><br>"; // } // $(".result").html(str); // } // if (arr2 != null) { // for (var j = 0; j " + arr2[j].name + "<span>" + arr2[j].area+ "</span><br>"; // } // $(".result2").html(str1); // } }, error:function(data){ alert("error"); } }) <p>frist:</p> <p>second:</p> for</arr1.length>
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='<p>'+ '</p><p>姓名:'+item.name+' 性别:'+item.sex+'</p>'+ '<p>like:'+item.like+'</p>'+ ''; $(".result").append(str); }) }, error:function(data){ alert("error"); } }) <p></p> eachPS: 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="爱我中华,虽远必诛
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!
Recommended reading:
Detailed explanation of JSON usage skills in JSSummary of jQuery operation json methodDetailed explanation of Jquery parsing Json string and Json array methodsThe above is the detailed content of Detailed explanation of the steps to convert Json objects and strings to each other. For more information, please follow other related articles on the PHP Chinese website!

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.

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

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.

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.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.


Hot AI Tools

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

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

Undress AI Tool
Undress images for free

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

SublimeText3 Chinese version
Chinese version, very easy to use

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver Mac version
Visual web development tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

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.
