Home Web Front-end JS Tutorial Implementation of methods for converting json strings and json objects into each other in js

Implementation of methods for converting json strings and json objects into each other in js

Jul 20, 2018 pm 02:53 PM

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
Copy after login

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
// ""
Copy after login

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"}"
Copy after login

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”属性值。
Copy after login

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);
Copy after login

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});
  // => &#39;{"Hello":123}&#39;
  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>
Copy after login

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!

Statement of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1252
29
C# Tutorial
1226
24
What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 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.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 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.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 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.

How to implement panel drag and drop adjustment function similar to VSCode in front-end development? How to implement panel drag and drop adjustment function similar to VSCode in front-end development? Apr 04, 2025 pm 02:06 PM

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...

See all articles