1. Create an object using JSON in javascript Js code
//Create an empty object
var JSONObject = {}
//Create a new object
var JSONObject = new Object()
/ /Create an object containing properties, where the name is a string and the age is an integer
var JSONObject = {
"name":"kevin",
"age":23
}
Similar to java, we can get the properties of an object through the dot (.) operator.
var JSONObject = {
"name":" kevin",
"age":24,
};
alert("JSONObject.name:" JSONObject.name);
alert("JSONObject.age:" JSONObject.age );
2. Use JSON to create array objects in javascript Create a Student object, which contains two array objects, each array object , contains the properties of the Student object.
var student = {
// The first array object Class
"Class":[
"{
"name":"kevin",
"className":"java",
"age":23
],
/ /The second array object
"Score":[
" {
" name": "shower",
"score":100
},
{
" name":"zheng",
"score":100
" " }
" " ]
}
var i=0;
for(i=0; i alert("student.Class[" i "].name===>" student.Class[i].name);
alert("student .Class[" i "].className===>" student.Class[i].className);
alert("student.Class[" i "].age===>" student.Class [i].age);
}
for(i=0;i alert("student.Score[" i "].name ===>" student.Score[i].name);
alert("student.Score[" i "].score===>" student.Score[i].score);
}
3. Use JSON to create messages in javascript
Copy code
The code is as follows:
//create a Student Object
var Student = {
"Math":[{
"name":"kevin",
"mark":70,
"age":23
},{
"name":"smart",
"mark":40,
"age":25
}
],
"Science":[{
"name":"kevin2",
"mark":70,
"age":23
},{
"name":"smart2",
"mark":40,
"age":25
}
]
}
//print array value
var i = 0;
var array = new Array();
for(i=0;i array.push(Student.Math[i].name);
array.push(Student.Math[i].mark);
array.push(Student.Math[i].age);
}
for(i=0;i array.push(Student.Science[i].name);
array.push(Student.Science[i].mark);
array.push(Student.Science[i].age);
}
alert("array==>" array);
//This method produce a JSON text from a JavaScript value.
//这个方法将一个JavaScript值转换为一个JSON字符串
alert("array.toJSONString()==>" array.toJSONString());
alert("String.parseJSON==>" array.toJSONString().parseJSON());
var data2 = array.toJSONString().parseJSON();
if(data2 instanceof Array){
alert("Array");
}
//表达式有浏览器兼容问题
//var cx = /[u0000u00adu0600-u0604u070fu17b4u17b5u200c-u200fu2028-u202fu2060-u206fufeffufff0-uffff]/g,
// escapable = /[\"x00-x1fx7f-x9fu00adu0600-u0604u070fu17b4u17b5u200c-u200fu2028-u202fu2060-u206fufeffufff0-uffff]/g,
//这个是修正后的
var cx = new RegExp('/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g'),
escapable = new RegExp('/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g'),