GVKun编程网logo

JSON.stringify深层对象(json.stringify深拷贝)

12

最近很多小伙伴都在问JSON.stringify深层对象和json.stringify深拷贝这两个问题,那么本篇文章就来给大家详细解答一下,同时本文还将给你拓展JavaScript对象与JSON格式的

最近很多小伙伴都在问JSON.stringify深层对象json.stringify深拷贝这两个问题,那么本篇文章就来给大家详细解答一下,同时本文还将给你拓展JavaScript对象与JSON格式的转换及JSON.stringify和JSON.parse的使用方法、JS 中 structuredClone 和 JSON.parse(JSON.stringify()) 克隆对象的区别、JSON Stringify从对象中删除数据、JSON 字符串转换为JavaScript 对象.JSON.parse()和JSON.stringify()等相关知识,下面开始了哦!

本文目录一览:

JSON.stringify深层对象(json.stringify深拷贝)

JSON.stringify深层对象(json.stringify深拷贝)

我需要一个从任何参数构建JSON有效字符串的函数,但:

  • 通过不两次添加对象来避免递归问题
  • 通过截断给定深度来避免调用堆栈大小问题

通常,它应该能够处理大对象,但要以截断为代价。

作为参考,此代码失败:

var json = JSON.stringify(window);

避免递归问题很简单:

var seen = [];return JSON.stringify(o, function(_, value) {    if (typeof value === ''object'' && value !== null) {        if (seen.indexOf(value) !== -1) return;        else seen.push(value);    }    return value;});

但是到目前为止,除了复制和更改Douglas
Crockford的代码以跟踪深度之外,我还没有找到任何方法来避免在诸如window或any之类的非常深的对象上发生堆栈溢出event。有一个简单的解决方案吗?

答案1

小编典典

我做了我最初担心的事情:我采用了Crockford的代码,并根据需要对其进行了修改。现在,它可以构建JSON但可以处理

  • 周期
  • 太深的物体
  • 数组太长
  • 异常(无法合法访问的访问器)

如果有人需要,我在GitHub上建立了一个GitHub存储库:JSON.prune

这是代码:

// JSON.pruned : a function to stringify any object without overflow// example : var json = JSON.pruned({a:''e'', c:[1,2,{d:{e:42, f:''deep''}}]})// two additional optional parameters ://   - the maximal depth (default : 6)//   - the maximal length of arrays (default : 50)// GitHub : https://github.com/Canop/JSON.prune// This is based on Douglas Crockford''s code ( https://github.com/douglascrockford/JSON-js/blob/master/json2.js )(function () {    ''use strict'';    var DEFAULT_MAX_DEPTH = 6;    var DEFAULT_ARRAY_MAX_LENGTH = 50;    var seen; // Same variable used for all stringifications    Date.prototype.toPrunedJSON = Date.prototype.toJSON;    String.prototype.toPrunedJSON = String.prototype.toJSON;    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,        escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,        meta = {    // table of character substitutions            ''\b'': ''\\b'',            ''\t'': ''\\t'',            ''\n'': ''\\n'',            ''\f'': ''\\f'',            ''\r'': ''\\r'',            ''"'' : ''\\"'',            ''\\'': ''\\\\''        };    function quote(string) {        escapable.lastIndex = 0;        return escapable.test(string) ? ''"'' + string.replace(escapable, function (a) {            var c = meta[a];            return typeof c === ''string''                ? c                : ''\\u'' + (''0000'' + a.charCodeAt(0).toString(16)).slice(-4);        }) + ''"'' : ''"'' + string + ''"'';    }    function str(key, holder, depthDecr, arrayMaxLength) {        var i,          // The loop counter.            k,          // The member key.            v,          // The member value.            length,            partial,            value = holder[key];        if (value && typeof value === ''object'' && typeof value.toPrunedJSON === ''function'') {            value = value.toPrunedJSON(key);        }        switch (typeof value) {        case ''string'':            return quote(value);        case ''number'':            return isFinite(value) ? String(value) : ''null'';        case ''boolean'':        case ''null'':            return String(value);        case ''object'':            if (!value) {                return ''null'';            }            if (depthDecr<=0 || seen.indexOf(value)!==-1) {                return ''"-pruned-"'';            }            seen.push(value);            partial = [];            if (Object.prototype.toString.apply(value) === ''[object Array]'') {                length = Math.min(value.length, arrayMaxLength);                for (i = 0; i < length; i += 1) {                    partial[i] = str(i, value, depthDecr-1, arrayMaxLength) || ''null'';                }                v = partial.length === 0                    ? ''[]''                    : ''['' + partial.join('','') + '']'';                return v;            }            for (k in value) {                if (Object.prototype.hasOwnProperty.call(value, k)) {                    try {                        v = str(k, value, depthDecr-1, arrayMaxLength);                        if (v) partial.push(quote(k) + '':'' + v);                    } catch (e) {                         // this try/catch due to some "Accessing selectionEnd on an input element that cannot have a selection." on Chrome                    }                }            }            v = partial.length === 0                ? ''{}''                : ''{'' + partial.join('','') + ''}'';            return v;        }    }    JSON.pruned = function (value, depthDecr, arrayMaxLength) {        seen = [];        depthDecr = depthDecr || DEFAULT_MAX_DEPTH;        arrayMaxLength = arrayMaxLength || DEFAULT_ARRAY_MAX_LENGTH;        return str('''', {'''': value}, depthDecr, arrayMaxLength);    };}());

一个可以做什么的例子:

var json = JSON.pruned(window);

注意:
与该答案中的代码相反,GitHub存储库在需要时进行更新(文档,兼容性,在commonjs或节点中用作模块,特定的序列化等)。如果需要此修剪功能,则从存储库开始是个好主意。

JavaScript对象与JSON格式的转换及JSON.stringify和JSON.parse的使用方法

JavaScript对象与JSON格式的转换及JSON.stringify和JSON.parse的使用方法

JSON处理

JSONJavaScript Object Notation)是JavaScript表达值和对象的通用数据格式,其本质就是符合一定规范的字符串。由于JSON的优良特性,非常容易和其他语言进行数据交换,尤其在前后端交互方面。即使我们前端使用JavaScript,后端使用Java/PHP/Python同样可以使用JSON格式的数据轻松交换。

JSON.stringify

JavaScript为我们提供了简单的方法可以实现对象和字符串之间的转化。

  • JSON.stringify将对象转为JSON字符串;
  • JSON.parseJSON字符串转为对象;

例如,我们把一个对象Dog使用 JSON.string转为JSON字符串:

let Dog = {
    name:''Peter'',
    age:187,
    gender:''male'',
    hands:[''hand01'',''hand02'',''hand03'',''hand04''],
    childs:[
        {
            name:''little peter01'',
            age:2,
            gender:''male'',
            hands:[''hand01'',''hand02'',''hand03'',''hand04''],
            childs:[]
        },
        {
            name:''little peter02'',
            age:3,
            gender:''male'',
            hands:[''hand01'',''hand02'',''hand03'',''hand04''],
            childs:[]
        }
    ]
}
let dogJson = JSON.stringify(Dog)
console.log(typeof dogJson)
console.log(dogJson)

代码的执行效果:

可见,使用JSON.stringify(obj)方法会返回该对象objJSON字符串数据,这个转换的过程可以称作JSON编码(JSON-encoded)序列化(serialized),亦或者编组化(marshalled)。当对象转为普通的字符串后,我们就可以以普通数据的格式存储、传递这些数据。

如果我们把这些字符串写入数据库,就相当于把JavaScript对象存进了数据库。

注意:

  • JSON编码的对象统一使用双引号,没有单引号和反引号;
  • 对象的属性名也用双引号,这是强制的;

JSON已经发展成为了独立的数据规范,因此归属于JavaScript语言本身的非数据属性会被JSON.stringify跳过。

包括:

  • 对象方法;
  • Symbol类型
  • undefined的属性
let user = {
    sayHello(){//函数被忽略
        console.log(''hello world'');
    },
    [Symbol(''id'')]:996996,//Symbol被忽略
    val:undefined//undefined值被忽略
}
console.log(JSON.stringify(user))

代码执行效果:

可以看到,里面啥也没有。

stringify的限制

并非所有的对象都能转为JSON格式,如果对象之间存在循环引用,就会导致转换失败。

let father = {}
let son = {}
father.son = son
son.father = father
JSON.stringify(father)

代码执行结果:

这里出现错误的原因就是存在对象间的循环引用,Father引用了Son,而Son又反过来引用了Father

排除和替换

如果我们只希望将对象的个别属性转为JSON格式,或者摆出循环应用中的属性,应该怎么做呢?

JSON.stringify已经为我们提供了解决方法:

let  json = JSON.stringify(obj[,replacer,space])

参数解读:

obj:要编码的对象replacer:要编码的属性数组或者映射函数function(k,v)space:用于格式化的空格数量

举个例子:

let father = {
    name:''father'',
    age:28
}
let son = {
    name:''son'',
    age:4
}
father.son = son;
son.father = father;
console.log(JSON.stringify(father,[''name'',''age'']))

代码的执行结果如下:

如果我们在第二个参数传入一个数组,那么JSON.stringify就会只把数组中的名称转为JSON格式,这样计算对象存在循环引用,同样能够成功的转格式。

如果我们希望序列化出循环应用外的所有对象属性,只需要把对象的所有属性名写入数组即可,这对对象的子对象同样生效。

举个例子:

let father = {
    name:''father'',
    age:28,
    car:{
        car_name : "BYD",
        car_age:3,
    }
}
console.log(JSON.stringify(father,[''name'',''car'',''car_name'']))

代码执行结果:

但是,还存在一个问题,如果对象属性特别多,可能数组就会非常长,代码也会很冗长。

这种情况下就需要使用映射函数

映射函数

我们可以创建一个函数,代替数组作为replacer,这个函数接收(key,value)作为参数,并决定如何序列化对应的属性。

例如,在解决循环引用的时候,我们排除引用属性:

let father = {
    name:''father'',
    age:28,
    car:{
    	car_name : "BYD",
        car_age:3,
	}
}
let son = {
    name:''son'',
    age:4
}
father.son = son;
son.father = father;
console.log(JSON.stringify(father,function replacer(key,value){
    console.log(`${key}:${value}`)
	return (key==''son'')?undefined:value;
}))

代码执行结果如下:

由于值为undefined的属性会被JSON.stringify忽略,这样我们就可以轻松的排除所有不希望出现的属性了。

格式化使用的空格数量

JSON.stringify(value, replacer, spaces)的第三个参数spaces可以指定JSON字符串的缩进空格数,常用的数值有2、4两种,相信童鞋们已经在编辑代码的时候有过修改缩进tab空格数的经历了。

在上文案例中,我们没有指定缩进空格数量,所以格式化后的JSON字符串都是没有格式的。

举个例子:

let Dog = {
    name:''Peter'',
    age:187,
    gender:''male'',
    hands:[''hand01'',''hand02'',''hand03'',''hand04''],
    childs:[
        {
            name:''little peter01'',
            age:2,
            gender:''male'',
            hands:[''hand01'',''hand02'',''hand03'',''hand04''],
            childs:[]
        },
        {
            name:''little peter02'',
            age:3,
            gender:''male'',
            hands:[''hand01'',''hand02'',''hand03'',''hand04''],
            childs:[]
        }
    ]
}
let dogJson = JSON.stringify(Dog,null,2)
console.log(dogJson)

代码的执行结果:

对比本文的第一个案例,是不是这样的缩进看起来好看多了呢?

自定义toJSON方法

在之前的文章中,我们讲到每个对象都有的toString方法,当进行格式转换时会自动调用。和toString一样,对象的toJSON方法会在序列化的时候调用,我们可以通过重写这个方法改变序列化的方式。

例如:

let dog = {
    name : ''peter'',
    age:18
}
console.log(JSON.stringify(dog))
dog.toJSON = function(){
    return this.age;
}
console.log(JSON.stringify(dog))

代码执行结果:

我们可以看到,在重写了对象的toJSON方法后,使用stringify的结果发生了改变。

我们可以根据自己的需要重写toJSON方法,从而达到自己的目的。

JSON.parse

上文讲到了如何使用JSON.stringify把对象转为JSON格式的字符串,这里就详细介绍如何把JSON字符串转为对象。

语法:

let obj = JSON.parse(str,[reviver])

str 要解析的 JSON 字符串。

reviver 可选的函数 function(key,value),该函数将为每个 (key, value) 对调用,并可以对值进行转换。

例如:

let str_arr = ''[1,2,3]''//数组字符串
let arr = JSON.parse(str_arr)
console.log(typeof arr)

代码执行结果:

对于复杂的嵌套对象:

let str_obj = `{
  "name": "Peter",
  "age": 187,
  "gender": "male",
  "hands": [
    "hand01",
    "hand02",
    "hand03",
    "hand04"
  ],
  "childs": [
    {
      "name": "little peter01",
      "age": 2,
      "gender": "male",
      "hands": [
        "hand01",
        "hand02",
        "hand03",
        "hand04"
      ],
      "childs": []
    },
    {
      "name": "little peter02",
      "age": 3,
      "gender": "male",
      "hands": [
        "hand01",
        "hand02",
        "hand03",
        "hand04"
      ],
      "childs": []
    }
  ]
}`
let obj = JSON.parse(str_obj)
console.log(obj.name)

代码执行结果:

注意:JSON不支持注释,在JSON中添加注释时错误的行为

有一种名为JSON5的格式,可以有不加引号的键、允许注释,但是这是独立的库,补上官方标准。

常规的JSON格式严格,这样是为了保证数据的可靠、快速解析算法

使用reviver

既然JSON.parse能够直接转字符串为对象,为啥还要再搞reviver呢?

场景举例:

如果我们有一个对象字符串如下:

// title: (meetup title), date: (meetup date)
let str = ''{"title":"Conference","date":"2017-11-30T12:00:00.000Z"}'';

现在我们要将它转为对象,存在什么问题呢?

let str = ''{"title":"Conference","date":"2017-11-30T12:00:00.000Z"}'';
let obj = JSON.parse(str)
obj.date.getDate();//Error

代码执行结果如下:

造成这种结果的原因是date属性被转为了字符串,而不是Date对象。

这个时候就需要我们使用reviver函数将date转为Date对象:

let str = ''{"title":"Conference","date":"2017-11-30T12:00:00.000Z"}'';
let obj = JSON.parse(str,function(key,value){
    if(key==''date'')return new Date(value)
    return value
})
obj.date.getDate();

代码执行效果:

顺便说一下,这也适用于嵌套对象:

let schedule = `{
  "meetups": [
    {"title":"Conference","date":"2017-11-30T12:00:00.000Z"},
    {"title":"Birthday","date":"2017-04-18T12:00:00.000Z"}
  ]
}`;

schedule = JSON.parse(schedule, function(key, value) {
  if (key == ''date'') return new Date(value);
  return value;
});

alert( schedule.meetups[1].date.getDate() ); // 正常运行了!

总结

  • JSON是一种数据格式,有独立的标准和大多数编程语言的支持
  • JSON支持Object、array、string、number、boolean和nullJ
  • SON.stringify
  • JSON.parse

到此这篇关于JavaScript对象与JSON格式的转换及JSON.stringify和JSON.parse的使用方法的文章就介绍到这了,更多相关JS与JSON格式转换内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

您可能感兴趣的文章:
  • 前端使用JSON.stringify实现深拷贝的巨坑详解
  • JavaScript语法 JSON序列化之stringify实例详解
  • JSON stringify及parse方法实现数据深拷贝
  • JS中的Error对象及使用JSON.stringify()序列化Error问题
  • 学习JSON.stringify的9大特性和转换规则
  • 比JSON.stringify快两倍的fast-json-stringify性能对比分析

JS 中 structuredClone 和 JSON.parse(JSON.stringify()) 克隆对象的区别

JS 中 structuredClone 和 JSON.parse(JSON.stringify()) 克隆对象的区别

JavaScript 中 structuredClone 和 JSON.parse(JSON.stringify()) 克隆对象的异同点

一、什么是 structuredClone?

1. structuredClone 的发展

structuredClone 是在 ECMAScript 2021(ES12)标准中引入的,ECMAScript 2021 规范正式发布于 2021 年 6 月

自 2022 年 3 月起,该功能适用于最新的设备和浏览器版本

Baseline 2022 Newly available
Since March 2022, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.

2. structuredClone 的功能

2.1. 功能

全局的 structuredClone() 方法使用结构化克隆算法将给定的值进行深拷贝

2.2. 语法
structuredClone(value)
structuredClone(value, { transfer })
2.2. 参数
  • value:被克隆的对象
  • transfer:可转移的数组
2.3. 返回值

返回值是原始值的深拷贝

2.4.

如果输入值的任一部分不可序列化,则抛出 DataCloneError 异常

3. 用法

3.1. 普通用法
const obj = {
  name: ''日升'',
  sex: ''男'',
  blog: {
      csdn: ''https://guoqiankun.blog.csdn.net/?type=blog'',
      jj: ''https://juejin.cn/user/2409752520033768/posts''
  },
  games: [''cf'', ''黑马喽'', ''cs''],
  age: 18,
  bool: true,
  set: new Set([1,2,3]),
  map: new Map([[''a'', ''b''], [''c'', ''d'']]),
  null: null,
  und: undefined
}
const cloneObj = structuredClone(obj);

3.2. transfer 用法

transfer 是一个可转移对象的数组,里面的值并没有被克隆,而是被转移到被拷贝对象上

const buffer = new ArrayBuffer(16);
console.log(''buffer'', buffer);
const cloned = structuredClone(buffer, { transfer: [buffer] });
console.log(''buffer'', buffer);
console.log(''cloned'', cloned);

二、structuredClone 和 JSON.parse(JSON.stringify()) 的区别

1. 支持的数据类型

从上面的示例中能看出,structuredClone 支持了很多中数据类型,基本类型和普通对象都支持

1.1. structuredClone
1.1.1. 支持的类型
  • 基本类型
  • 普通对象
  • Date 对象
  • RegExp 对象
  • Map
  • Set
  • ArrayBuffer
  • TypedArrays
  • Blob
  • File
  • ImageData
  • MessagePort
  • null、undefined
  • NaN、Infinity、-Infinity
  • 循环引用
1.1.2. 不支持的类型
  • 函数
  • symbol
  • WeakMap
  • WeakSet
  • HTMLElement
1.1.3. 示例
const port1 = new MessageChannel().port1
const obj = {
  date: new Date(),
  regex: /test/i,
  map: new Map([[''key1'', ''value1''], [''key2'', ''value2'']]),
  set: new Set([1, 2, 3]),
  arrayBuffer: new ArrayBuffer(8),
  typedArray: new Uint8Array([1, 2, 3]),
  blob: new Blob([''Hello, world!''], { type: ''text/plain'' }),
  file: new File([''file content''], ''filename.txt'', { type: ''text/plain'' }),
  imageData: (() => {
    const canvas = document.createElement(''canvas'');
    const context = canvas.getContext(''2d'');
    return context.createImageData(100, 100);
  })(),
  messagePort: port1,
  nullValue: null,
  undefinedValue: undefined,
  nanValue: NaN,
  infinityValue: Infinity,
  negativeInfinityValue: -Infinity,
  circularRef: {}
};

// 创建循环引用
obj.circularRef.self = obj;

// 克隆 obj 对象
const clonedObj = structuredClone(obj, {transfer: [port1]});

// 输出以验证
console.log(clonedObj);

const obj = {
  func: function() { return "I''m a function"; },   // 函数
  symbol: Symbol(''uniqueSymbol''),                  // Symbol
  weakMap: new WeakMap(),                          // WeakMap
  weakSet: new WeakSet(),                          // WeakSet
  element: document.createElement(''div'')           // HTMLElement
};

// 尝试克隆对象
try {
  const clonedObj = structuredClone(obj);
  console.log(clonedObj); // This line won''t run if an error is thrown
} catch (error) {
  console.error(''Error:'', error); // DataCloneError: Failed to execute ''structuredClone''
}

1.2. JSON.parse(JSON.stringify())
1.2.1. 支持的类型
  • 数字
  • 字符串
  • 布尔值
  • 数组
  • 普通对象
1.2.2. 不支持的类型
  • Date、Map、Set、RegExp、Function、undefined、symbol、Infinity、NaN、循环引用...

JSON.stringify 详细信息可以看下下面的文章

【你需要了解的JSON.stringify()】

1.2.3. 示例
JSON.parse(JSON.stringify({
  a: null,
  b: undefined,
  c: NaN,
  d: Infinity,
  e: () => ({}),
  f: new Map(),
  g: new Set(),
  h: Symbol(''a''),
  i: Infinity
}))

// 返回值

{
  "a": null,
  "c": null,
  "d": null,
  "f": {},
  "g": {},
  "i": null
}

2. 循环引用

2.1. structuredClone

可以正确处理对象中的循环引用

2.2. JSON.parse(JSON.stringify)

如果对象中存在循环引用,调用 JSON.stringify 会抛出错误,导致克隆失败

3. 性能方面

3.1. structuredClone

通常在处理复杂对象时性能更优,特别是包含大量非 JSON 兼容类型的数据时,因为它是为深度克隆设计的原生方法,内部优化了许多复杂场景

3.2. JSON.parse(JSON.stringify)

在处理简单的、JSON 兼容的数据结构时可能性能较好,但在处理复杂对象或非 JSON 兼容类型时效率低下

4. 浏览器兼容

4.1. structuredClone

是一种较新的 API,在某些较旧的浏览器中不被支持

4.2. JSON.parse(JSON.stringify)

在现代浏览器和较旧的浏览器中都有广泛支持

三、总结

  • structuredClone 提供了更广泛的数据类型支持和对循环引用的处理能力,适用于复杂场景
  • JSON.parse(JSON.stringify) 适合处理简单、JSON 兼容的数据结构,但在处理复杂数据类型或循环引用时有局限性
  • 两者都有限制,克隆的时候需要关注下克隆对象的数据类型再做选择

参考

  • 【structuredClone】
  • 【你需要了解的JSON.stringify()】

JSON Stringify从对象中删除数据

JSON Stringify从对象中删除数据

我正在通过jQuery ajax将JSON发送到Node服务器。我的jQuery ajax正在运行。见下文。

var user = JSON.stringify(userObject);
$.ajax({
        type: 'POST',url: 'http://localhost:5000/save',contentType: 'application/json',dataType: 'json',data: user
    })
    .done(function(data) {
        console.log(data.link,'here is the link');
        callback(data.link);
    })
    .fail(function(err) {
        console.log(err);
        callback(err);
    });

我的问题是,当我控制台日志用户(一个已字符串化的json对象)时,我在丢失的数组中有信息。我丢失的对象部分看起来像这样。

失去这部分

它在控制台中显示为字符串形式,如下所示:

字符串化控制台日志

不会存储在父用户对象内部的那些数组中存储的信息。关于为什么会这样的任何建议都会有所帮助。如果您有其他方法可用于通过jQuery
ajax发送此数据结构,请告诉我。

编辑 这是创建区域的位置:

// Add regions to the bracket layout object
        user.regions = [];
        for (var a = 0; a < 2; a++) {
            user.regions[a] = [];
            user.regions[a].columns = [];
        }

谢谢,

JSON 字符串转换为JavaScript 对象.JSON.parse()和JSON.stringify()

JSON 字符串转换为JavaScript 对象.JSON.parse()和JSON.stringify()

使用 JavaScript 内置函数 JSON.parse() 将字符串转换为 JavaScript 对象:

text = '{ "sites" : [' + '{ "name":"Runoob","url":"www.runoob.com" },' + '{ "name":"Google","url":"www.google.com" },' + '{ "name":"Taobao","url":"www.taobao.com" } ]}'obj =<span><span> JSON.parse(text);
console.log(obj.sites[1].name);<span>//<span>Google
console.log(obj.sites[1].url);<span>//<span>www.google.com

用于将 JavaScript 值转换为 JSON 字符串。

语法

JSON.stringify(value[,replacer[,space]])

value:
必需, 一个有效的 JSON 字符串。

replacer:
可选。用于转换结果的函数或数组。

如果 replacer 为函数,则 JSON.stringify 将调用该函数,并传入每个成员的键和值。使用返回值而不是原始值。如果此函数返回 undefined,则排除成员。根对象的键是一个空字符串:""。

如果 replacer 是一个数组,则仅转换该数组中具有键值的成员。成员的转换顺序与键在数组中的顺序一样。当 value 参数也为数组时,将忽略 replacer 数组。

space:
可选,文本添加缩进、空格和换行符,如果 space 是一个数字,则返回值文本在每个级别缩进指定数目的空格,如果 space 大于 10,则文本缩进 10 个空格。space 有可以使用非数字,如:\t。

实例

str = {"name":"菜鸟教程","site":"http://www.runoob.com" document.write( "只有一个参数情况:""
""
" + str_pretty1 + "
""
" document.write( "使用参数情况:""
""
" + str_pretty2 + "
" ); 输出

测试结果

一个参数情况: {"name":"菜鸟教程","site":"http://www.runoob.com"<span>//<span>使用参数情况:
<span>{
"name": "菜鸟教程"<span>,"site": "http://www.runoob.com"<span>
}

JSON.parse()和JSON.stringify(),这两个JavaScript内置的方法,对低版本浏览器不兼容,。

需要引入JSON2.js插件

今天关于JSON.stringify深层对象json.stringify深拷贝的讲解已经结束,谢谢您的阅读,如果想了解更多关于JavaScript对象与JSON格式的转换及JSON.stringify和JSON.parse的使用方法、JS 中 structuredClone 和 JSON.parse(JSON.stringify()) 克隆对象的区别、JSON Stringify从对象中删除数据、JSON 字符串转换为JavaScript 对象.JSON.parse()和JSON.stringify()的相关知识,请在本站搜索。

本文标签:

上一篇JavaScript全屏iframe,高度为100%(iframe全屏代码)

下一篇如何使用Newtonsoft JSON.NET执行提供“路径”的部分对象序列化(对象实现序列化接口)