JSON.Stringfy方法的replacer参数不适用于嵌套对象

时间:2018-08-03 12:13:25

标签: javascript typescript

我有一个对象,我想将此对象的简化版本发送到服务器。

{
 "fullName": "Don Corleone",
 "actor": {
  "actorId": 2,
  "name": "Marlon",
  "surname": "Brando",
  "description": "Marlon Brando is widely considered the greatest movie actor of all time... ",
  "heroList": [],
  "photo": "C:\\projects\\files\\actor\\1532955376934.png"
 },
 "heroProfilePhoto": "data:image/png;base64,/9j/...
 "production": {
  "title": "The Godfather",
  "imdbRate": 9.2,
  "genre": "8",
  "releaseDate": "1972-03-23T21:00:00.000Z",
  "director": "Francis Ford Coppola",
  "writer": "Mari Puzo",
  "detail": "The aging patriarch of an organized crime dynasty transfers control of his clandestine empire to his reluctant son."
 }
}"

我有两个问题:

1)是否可以用replacer parameter中的JSON.stringify()提取类似的东西?

 {
  "fullName": "Don Corleone",
  "actor": {
   "actorId": 2
   }
}"

2)至少我可以用replacer parameterJSON.stringify()提取类似的东西吗?

{
 "fullName": "Don Corleone",
 "actor": {
  "actorId": 2,
  "name": "Marlon",
  "surname": "Brando",
  "description": "Marlon Brando is widely considered the greatest movie actor of all time... ",
  "heroList": [],
  "photo": "C:\\projects\\files\\actor\\1532955376934.png"
 },
}"

当我这样使用时,可以:

JSON.stringify(hero, ['fullName'])结果-> "{"fullName":"Don Corleone"}"

但是这个:

JSON.stringify(hero, ['fullName', 'actor'])结果-> "{"fullName":"Don Corleone","actor":{}}"

为什么actor属性为空?

2 个答案:

答案 0 :(得分:6)

JSON.stringify要求您传递您要返回的所有数据。仅靠'actor'是不够的。

您要

JSON.stringify(hero, ['fullName', 'actor', 'actorId'])

编辑

因此,我已经进行了一些测试,我很好奇如果actorId也存在于父对象中并且结果在其中会发生什么情况。

actorId对象内部和父对象内部存在actorId的情况下,JSON.stringify()返回两个actor字段。如果您不希望出现这种情况,则必须根据需要创建一个更复杂的函数,并将其传递给JSON.stringify(),如here

所述。

以下是一些示例:

var json = {
    key1: "Value for key1 in parent",
    key2: {
        key3: "Value for key3 in child",
        key4: "Value for key4 in child"
    },
    key4: "Value for key4 in parent"
}

var out1 = JSON.stringify(json, ['key1', 'key3'])
/*
out1 = {
    key1: "Value for key1 in parent"
} // No key3!
*/


var out2 = JSON.stringify(json, ['key1', 'key2', 'key3'])
/*
out2 = {
    key1: "Value for key1 in parent",
    key2: {
        key3: "Value for key3 in child"
    }
}
*/

var out3 = JSON.stringify(json, ['key1', 'key2', 'key3', 'key4'])
/*
out3 = {
    key1: "Value for key1 in parent",
    key2: {
        key3: "Value for key3 in child",
        key4: "Value for key4 in child" // Both key4 returned
    },
    key4: "Value for key4 in parent" // Both key4 returned
}
*/

答案 1 :(得分:0)

我们可以轻松地在对象文字中使用Spread

尝试像读取对象一样

const obj = {yourObj.fullname, yourObj.actor} const yourAnswer = JSON.stringify(obj)

您可以参考链接 Spread_syntax

由于JSON.stringify对于大型对象非常慢,请尝试使用上述方法