


Implementation of methods for converting json strings and json objects into each other in js
In the process of using js to develop, json strings and json objects need to be converted into each other. So how are json strings converted into json objects and json objects converted into json strings? Next, I will show you a specific example.
1. Convert JSON string to JSON object
var obj = JSON.parse(str[, reviver]);
Example:
JSON.parse('{}'); // {} JSON.parse('true'); // true JSON.parse('"foo"'); // "foo" JSON.parse('[1, 5, "false"]'); // [1, 5, "false"] JSON.parse('null'); // null JSON.parse('1'); // 1
reviver: If it is a function, it returns after executing its method on the original value before being returned.
Parse the JSON string and return the corresponding value. You can pass in an additional conversion function to make certain modifications to the generated value and its attributes before returning it. The parameters k and v of the function represent the returned attribute name and attribute value respectively
JSON.parse('{"p": 5}', function (k, v) { if(k === '') return v; // 如果到了最顶层,则直接返回属性值, return v * 2; // 否则将属性值变为原来的 2 倍。 }); // { p: 10 } JSON.parse('{"1": 1, "2": 2,"3": {"4": 4, "5": {"6": 6}}}', function (k, v) { console.log(k); // 输出当前的属性名,从而得知遍历顺序是从内向外的, // 最后一个属性名会是个空字符串。 return v; // 返回原始属性值,相当于没有传递 reviver 参数。 }); // 1 // 2 // 4 // 6 // 5 // 3 // ""
2. Convert the JSON object into a JSON string.
JSON.stringify(value[, replacer [, space]])
value will be serialized into a JSON string value.
replacer Optional If this parameter is a function, during the serialization process, each attribute of the serialized value will be converted and processed by the function.
space optionally specifies the blank string used for indentation, which is used to beautify the output (pretty-print); if the parameter is a number, it represents the number of spaces; the upper limit is 10. If the value is less than 1, it means there are no spaces; if the parameter is a string (the first ten letters of the string), the string will be treated as spaces; if the parameter is not provided (or is null) there will be no spaces. Example:
JSON.stringify({}); // '{}' JSON.stringify(true); // 'true' JSON.stringify("foo"); // '"foo"' JSON.stringify([1, "false", false]); // '[1,"false",false]' JSON.stringify({ x: 5 }); // '{"x":5}' JSON.stringify({x: 5, y: 6}); // "{"x":5,"y":6}" JSON.stringify([new Number(1), new String("false"), new Boolean(false)]); // '[1,"false",false]' JSON.stringify({x: undefined, y: Object, z: Symbol("")}); // '{}' JSON.stringify([undefined, Object, Symbol("")]); // '[null,null,null]' JSON.stringify({[Symbol("foo")]: "foo"}); // '{}' JSON.stringify({[Symbol.for("foo")]: "foo"}, [Symbol.for("foo")]); // '{}' JSON.stringify( {[Symbol.for("foo")]: "foo"}, function (k, v) { if (typeof k === "symbol"){ return "a symbol"; } } ); // undefined // 不可枚举的属性默认会被忽略: JSON.stringify( Object.create( null, { x: { value: 'x', enumerable: false }, y: { value: 'y', enumerable: true } } ) ); // "{"y":"y"}"
If replacer is an array, the value of the array represents the attribute name that will be serialized into a JSON string.
JSON.stringify(foo, ['week', 'month']); // '{"week":45,"month":7}', 只保留“week”和“month”属性值。
3. Use JSON.stringify combined with localStorage local storage
Sometimes, you want to store an object created by the user, and the object can still be restored even after the browser is closed. The following example is a template for JSON.stringify suitable for this situation:
// 创建一个示例数据 var session = { 'screens' : [], 'state' : true }; session.screens.push({"name":"screenA", "width":450, "height":250}); session.screens.push({"name":"screenB", "width":650, "height":350}); session.screens.push({"name":"screenC", "width":750, "height":120}); session.screens.push({"name":"screenD", "width":250, "height":60}); session.screens.push({"name":"screenE", "width":390, "height":120}); session.screens.push({"name":"screenF", "width":1240, "height":650}); // 使用 JSON.stringify 转换为 JSON 字符串 // 然后使用 localStorage 保存在 session 名称里 localStorage.setItem('session', JSON.stringify(session)); // 然后是如何转换通过 JSON.stringify 生成的字符串,该字符串以 JSON 格式保存在 localStorage 里 var restoredSession = JSON.parse(localStorage.getItem('session')); // 现在 restoredSession 包含了保存在 localStorage 里的对象 console.log(restoredSession);
4. Polyfill for support of older versions below IE8
JSON objects may not be supported by older versions of browsers . You can put the following code at the beginning of the JS script so that you can use JSON objects in browsers that do not natively support JSON objects (such as IE6).
The following algorithm is an imitation of the native JSON object:
You can also introduce the cdn of JSON3.js
<script src="//cdnjs.cloudflare.com/ajax/libs/json3/3.3.2/json3.min.js"></script> <script> JSON.stringify({"Hello": 123}); // => '{"Hello":123}' JSON.parse("[[1, 2, 3], 1, 2, 3, 4]", function (key, value) { if (typeof value == "number") { value = value % 2 ? "Odd" : "Even"; } return value; }); // => [["Odd", "Even", "Odd"], "Odd", "Even", "Odd", "Even"] </script>
Related recommendations:
js Method analysis to convert json string to json object
The above is the detailed content of Implementation of methods for converting json strings and json objects into each other in js. 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











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.

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.

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.

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.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

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

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 does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.
