The JSON format originates from objects and arrays in JavaScript, so js is naturally the simplest and most primitive to operate. Next, let’s look at some commonly used examples of basic operations on JSON objects in JavaScript
JSON object
1. Object attributes:
The object attributes are composed of key-value pairs, where key is a string and value can be for any Javascript object.
//使用[]设置和获取对象的属性 var obj = new Object(); obj["www.jb51.net"] = "http://www.jb51.net"; alert(obj["www.jb51.net"]);
2. Variables are attributes:
The Javascript engine will build a global object during initialization, and all variables are Properties of this global object. In order to reference this global object, you can get it in the top-level scope like this:
var global = this;
In Javascript, any independent function or variable belongs to the properties of this object , that is:
function test(){}
is equivalent to:
window.test = function(){}
3. Use Object:
Three ways to declare an object:
① Create an Object object through the new operator, and then dynamically add attributes to construct an object from scratch
② Define the object Class circle, and then use the new operator to construct new objects in batches
//创建一个对象 function User(username, password){ this.username = username; this.password = password; this.getUsername = function(){ return this.username; } this.getPassword = function(){ return this.password; } } var arthinking = new User("Jason", "123"); alert(arthinking.getUsername()); alert(arthinking.getPassword());
③ Construct objects using JSON
JSON is Javascript object Representation method (Javascript Object Notation), that is, representing an object through literals:
//JSON形式创建一个对象 var arthinking = { username : "Jason", password : "123", favorite : { sports : "football", music : "Guitar" } } alert(arthinking.username); alert(arthinking.favorite.sports);
Parse the JSON format data returned by the server
Single JSON Object:
[{a:'1',b'2'},{a:'3',b'4'}]
Multiple JSON objects:
{ "usergroups":[{a:'001',b:'arthinking'},a:'002',b:'Jason'}], "groups":[{c:'001',d:'IT宅'}] }
The data that needs to be transmitted can be encapsulated from the backend according to this format. After the frontend obtains it, it can parse and obtain the data like this:
//假设response.responseText为返回的JSON字符串 //可以使用eval()函数把JSON字符串转换成Javascript语句 //再通过”.”导航获取具体属性,length属性为对象的长度 var obj = eval( "(" + response.responseText + ")" ); for(var i = 0; i Copy after login
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
javascriptImplementing the Map object function in Java (detailed answer, code attached)
Seven ways to create objects in JavaScript (summary, must read)
JavaScript constructor and new operator (emphasis, must read)
The above is the detailed content of Examples of basic operations on JSON objects in JavaScript (graphic tutorial). For more information, please follow other related articles on the PHP Chinese website!