search
HomeWeb Front-endJS TutorialJSON object use case (with code)

JSON object use case (with code)

Apr 24, 2018 pm 05:15 PM
javascriptjsoncode

This time I will bring you a JSON object usage case (with code). What are the precautions for using JSON objects? The following is a practical case, let’s take a look.

Previous words

The full name of json (javascript object notation) is javascript object notation. It is a text format for data exchange, and Not a programming language for reading structured data. It was proposed by Douglas Crockford in 2001 with the purpose of replacing the cumbersome and cumbersome XML format. This article will introduce in detail the content of json

Grammar rules

The syntax of JSON can represent the following three types of values

[1] Simple value

Simple values ​​use the same syntax as JavaScript and can represent strings, numeric values, Boolean values, and null in JSON

Strings must be represented by double quotes, single quotes cannot be used. The value must be expressed in decimal, and NaN and Infinity

cannot be used [Note] JSON does not support the special value undefined

//合格的简单值
5
"hello world"
true
null
//不合格的简单值
+0x1
'hello world'
undefined
NaN
Infinity

[2] Object

The object is used as an A complex data type that represents an ordered set of key-value pairs. The value in each key-value pair can be a simple value or a complex data type value

Compared with JavaScript object literals, json has three differences

1. JSON does not have the concept of variables

2. In JSON, the key name of the object must be placed in double quotes

3. Because JSON is not a javascript statement, there is no semicolon at the end

[Note] Two properties with the same name should not appear in the same object

//合格的对象
{
  "name":"huochai",
  "age":29,
  "school":{
    "name":"diankeyuan",
    "location":"beijing"
  }
}
//不合格的对象
{ name: "张三", 'age': 32 }//属性名必须使用双引号
{};//不需要末尾的分号
{ "birthday": new Date('Fri, 26 Aug 2011 07:13:10 GMT'),
 "getName": function() {
   return this.name;
 }
} // 不能使用函数和日期对象

[3] Array

Array is also a complex data type, representing a set of ordered values. A list whose values ​​can be accessed by numeric index. The value of the array can also be of any type - simple value, object or array

JSON array also has no variables and semicolons. Combining arrays and objects can form more complex data collections

[Note] A comma cannot be added after the last member of an array or object

JSON object

The reason why JSON is popular is that the JSON data structure can be parsed as Useful javascript objects

ECMAScript5 standardizes the behavior of parsing JSON and defines the global object JSON

[Note] IE7-browser does not support

There are two JSON objects Methods: stringify() and parse(). These two methods are used to serialize JavaScript objects into JSON strings and parse JSON strings into native JavaScript values

stringify()

 JSON.stringify () method is used to convert a value into a string. The string should conform to JSON format and can be restored by the JSON.parse() method

By default, the JSON string output by JSON.stringify() does not include any space characters or indentation

var jsonObj = {
  "title":"javascript",
  "group":{
    "name":"jia",
    "tel":12345
  }
};
//{"title":"javascript","group":{"name":"jia","tel":12345}}
JSON.stringify(jsonObj);

Specific conversion

JSON.stringify('abc') // ""abc""
JSON.stringify(1) // "1"
JSON.stringify(false) // "false"
JSON.stringify([]) // "[]"
JSON.stringify({}) // "{}"
JSON.stringify([1, "false", false])// '[1,"false",false]'
JSON.stringify({ name: "张三" })// '{"name":"张三"}'

The stringify() method converts regular expressions and mathematical objects into the string form of empty objects

JSON.stringify(/foo/) // "{}"
JSON.stringify(Math) // "{}"

The stringify() method converts date objects and wrapper objects into strings

JSON.stringify(new Boolean(true)) //"true"
JSON.stringify(new String('123')) //""123""
JSON.stringify(new Number(1)) //"1"
JSON.stringify(new Date()) //""2016-09-20T02:26:38.294Z""

If the member of the object is undefined or a function, this member will be omitted

If the member of the array is undefined or a function, Then these values ​​are converted to null

JSON.stringify({
 a: function(){},
 b: undefined,
 c: [ function(){}, undefined ]
});
// "{"c":[null,null]}"

The JSON.stringify() method will ignore the non-traversable properties of the object

var obj = {};
Object.defineProperties(obj, {
 'foo': {
  value: 1,
  enumerable: true
 },
 'bar': {
  value: 2,
  enumerable: false
 }
});
JSON.stringify(obj); // {"foo":1}]

Parameters

JSON.stringify In addition to the JavaScript object to be serialized, () can also receive two other parameters, which are used to specify different ways to serialize the JavaScript object. The first parameter is a filter, which can be an array or a function; the second parameter is an option, indicating whether to retain indentation in the JSON string

[Array Filter]

When the second parameter of the stringify() method is an array, it is equivalent to implementing the function of a filter

  【1】过滤器只对对象的第一层属性有效

var jsonObj = {
  "title":"javascript",
  "group":{
    "a":1
  }
};
//{"group":{"a":1}}
console.log(JSON.stringify(jsonObj,["group","a"]))

  【2】过滤器对数组无效

var jsonObj =[1,2];
JSON.stringify(jsonObj,["0"])//"[1,2]"

函数参数

  stringify()方法的第二个参数也可以是一个函数。传入的函数接收两个参数,属性(键)名和属性值

JSON.stringify({a:1,b:2}, function(key, value){
 if (typeof value === "number") {
  value = 2 * value;
 }
 return value;  
})
// "{"a":2,"b":4}"

  属性名只能是字符串,而在值并非键值对儿结构的值时,键名可以是空字符串

  这个函数参数会递归处理所有的键

  下面代码中,对象o一共会被f函数处理三次。第一次键名为空,键值是整个对象o;第二次键名为a,键值是{b:1};第三次键名为b,键值为1

JSON.stringify({a: {b: 1}}, function (key, value) {
 console.log("["+ key +"]:" + value);
 return value;
})
// []:[object Object]
// [a]:[object Object]
// [b]:1
// '{"a":{"b":1}}'

  函数返回的值就是相应键的值。如果函数返回了undefined或没有返回值,那么相应的属性会被忽略

JSON.stringify({ a: "abc", b: 123 }, function (key, value) {
 if (typeof(value) === "string") {
  return undefined;
 }
 return value;
})
// '{"b": 123}'

【缩进】

  stringify()方法还可以接受第三个参数,用于增加返回的JSON字符串的可读性

  如果是数字,表示每个属性前面添加的空格(最多不超过10个)

  如果是字符串(不超过10个字符),则该字符串会添加在每行前面

/*"{
 "p1": 1,
 "p2": 2
}"*/
JSON.stringify({ p1: 1, p2: 2 }, null, 2);
//"{"p1":1,"p2":2}"
JSON.stringify({ p1: 1, p2: 2 }, null, 0);
/*"{
|-"p1": 1,
|-"p2": 2
}"*/
JSON.stringify({ p1:1, p2:2 }, null, '|-');
toJSON()

  有时候,JSON.stringify()还是不能满足对某些对象进行自定义序列化的需求。在这些情况下, 可以通过对象上调用toJSON()方法,返回其自身的JSON数据格式

JSON.stringify({
 toJSON: function () {
  return "Cool"
 }
})
// ""Cool""
var o = {
 foo: 'foo',
 toJSON: function() {
  return 'bar';
 }
};
JSON.stringify({x: o});// '{"x":"bar"}'

  如果toJSON()方法返回undefined,此时如果包含它的对象嵌入在另一个对象中,会导致该对象的值变成null。而如果包含它的对象是顶级对象,结果就是undefined

JSON.stringify({
 toJSON: function () {
  return undefined
 }
})
//undefined

  Date对象部署了一个自己的toJSON方法,自动将Date对象转换成日期字符串

JSON.stringify(new Date("2016-08-29"))
// "2016-08-29T00:00:00.000Z"

  toJSON方法的一个应用是,可以将正则对象自动转为字符串

RegExp.prototype.toJSON =RegExp.prototype.toString;
JSON.stringify(/foo/)// ""/foo/""

  toJSON()可以作为函数过滤器的补充,因此理解序列化的内部顺序十分重要。假设把一个对象传入JSON.stringify(),序列化该对象的顺序如下

  1、如果存在toJSON()方法而且能通过它取得有效的值,则调用该方法。否则,按默认顺序执行序列化

  2、如果提供了第二个参数,应用这个函数过滤器。传入函数过滤器的值是第一步返回的值

  3、对第二步返回的每个值进行相应的序列化

  4、如果提供了第三个参数,执行相应的格式化

parse()

  JSON.parse方法用于将JSON字符串转化成对象

JSON.parse('{}') // {}
JSON.parse('true') // true
JSON.parse('"foo"') // "foo"
JSON.parse('[1, 5, "false"]') // [1, 5, "false"]
JSON.parse('null') // null
var o = JSON.parse('{"name": "张三"}');
o.name // 张三

  如果传入的字符串不是有效的JSON格式,JSON.parse方法将报错

//Uncaught SyntaxError: Unexpected token u in JSON at position 0(…)JSON.parse("'String'")
//Uncaught SyntaxError: Unexpected token u in JSON at position 0(…)JSON.parse("undefined")

  JSON.parse()方法也可以接收一个函数参数,在每个键值对儿上调用,这个函数被称为还原函数(reviver)。该函数接收两个参数,一个键和一个值,返回一个值

  如果还原函数返回undefined,则表示要从结果中删除相应的键;如果返回其他值,则将该值插入到结果中

var o = JSON.parse('{"a":1,"b":2}', function(key, value) {
 if (key === ''){
  return value;
 }
 if (key === 'a') {
  return value + 10;
 }
});
o.a // 11
o.b // undefinef

  在将日期字符串转换为Date对象时,经常要用到还原函数

var book = {
  "title": "javascript",
  "date": new Date(2016,9,1)
}
var jsonStr = JSON.stringify(book);
//'{"title":"javascript","date":"2016-09-30T16:00:00.000Z"}''
console.log(jsonStr)
var bookCopy = JSON.parse(jsonStr,function(key,value){
  if(key == 'date'){
    return new Date(value);
  }
  return value;
})
console.log(bookCopy.date.getFullYear());//2016

eval()

  实际上,eval()类似于JSON.parse()方法,可以将json字符串转换为json对象

eval('(' + '{"a":1}'+')').a;//1
JSON.parse('{"a":1}').a;//1

  但是,eval()可以执行不符合JSON格式的代码,有可能会包含恶意代码

eval('(' + '{"a":alert(1)}'+')').a;//弹出1
JSON.parse('{"a":alert(1)}').a;//报错

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

jquery中ajax执行顺序调整

Ajax与$.ajax实例详解

The above is the detailed content of JSON object use case (with code). For more information, please follow other related articles on the PHP Chinese website!

Statement
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
From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)