


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);
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原生的方法,需要引入相应的库或自己定义后才能用 (不习惯用)
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":"山东"}, ] }
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='<p style="display:block">'+ '<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>'+ '</p>'; } $(".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"); } }) <p class="result">frist:</p> <p class="result2">second:</p> for
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 style="display:block">'+ '<p>姓名:'+item.name+' 性别:'+item.sex+'</p>'+ '<p>like:'+item.like+'</p>'+ '</p>'; $(".result").append(str); }) }, error:function(data){ alert("error"); } }) <p class="result"></p> each
##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="爱我中华,虽远必诛
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!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











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.

Detailed explanation of the method of converting int type to string in PHP In PHP development, we often encounter the need to convert int type to string type. This conversion can be achieved in a variety of ways. This article will introduce several common methods in detail, with specific code examples to help readers better understand. 1. Use PHP’s built-in function strval(). PHP provides a built-in function strval() that can convert variables of different types into string types. When we need to convert int type to string type,

1. First open pycharm and enter the pycharm homepage. 2. Then create a new python script, right-click - click new - click pythonfile. 3. Enter a string, code: s="-". 4. Then you need to repeat the symbols in the string 20 times, code: s1=s*20. 5. Enter the print output code, code: print(s1). 6. Finally run the script and you will see our return value at the bottom: - repeated 20 times.

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

PHP String Operation: Remove Extra Commas and Keep Only Commas Implementation Tips In PHP development, string processing is a very common requirement. Sometimes we need to process the string to remove extra commas and retain the only commas. In this article, I'll introduce an implementation technique and provide concrete code examples. First, let's look at a common requirement: Suppose we have a string containing multiple commas, and we need to remove the extra commas and keep only the unique comma. For example, replace "apple,ba

Strings in GoLang, although immutable, can be dynamically modified using the following technique: concatenating strings using string concatenation. Create a new string using string formatting. Modify the underlying byte slice of the string. Use mutable string types provided by third-party libraries.

As a scripting language widely used to develop web applications, PHP has very powerful string processing functions. In daily development, we often encounter operations that require deleting a string, especially the last two characters of the string. This article will introduce two PHP techniques for deleting the last two characters of a string and provide specific code examples. Tip 1: Use the substr function The substr function in PHP is used to return a part of a string. We can easily remove characters by specifying the string and starting position

Converting a string to a floating point number is a common operation in PHP and can be accomplished through built-in methods. First make sure that the string is in a legal floating point format before it can be successfully converted to a floating point number. The following will detail how to convert a string to a floating point number in PHP and provide specific code examples. 1. Use (float) cast In PHP, the simplest way to convert a string into a floating point number is to use cast. The way to force conversion is to add (float) before the string, and PHP will automatically convert it
