javascript - JSON.Stringfy 方法的替换参数不适用于嵌套对象
问题描述
我有一个对象,我想将这个对象的简化版本发送到服务器。
{
"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)是否可以使用JSON.stringify()的replacer 参数提取类似的内容?
{
"fullName": "Don Corleone",
"actor": {
"actorId": 2
}
}"
2)至少我可以用JSON.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":{}}"
为什么演员属性是空的?
解决方案
JSON.stringify
要求您传递您想要返回的所有数据。'actor'
光靠自己是不够的。
你要:
JSON.stringify(hero, ['fullName', 'actor', 'actorId'])
编辑
所以我做了一些测试,我很好奇如果actorId
父对象中也存在会发生什么,结果在。
在对象内部和父对象内部存在的情况下,这两个actorId
字段都由 JSON.stringify() 返回。如果您不希望出现这种情况,则必须根据需要创建一个更复杂的函数并将其传递给 JSON.stringify(),如此处所述actorId
actor
这里有一些例子:
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
}
*/
推荐阅读
- sql - regex_replace 追加到行尾?
- rest - 无服务器 Watson 部署?(关于与其他 RESTful 服务集成的问题)
- .htaccess - Magento
我正在尝试使用 magento 设置 WAMP 服务器,但是每当我尝试访问本地主机中的 magento 文件夹时,我都会收到内部错误。
当我阅读 Apache
- r - 如何在 r 中融化我的数据框
- ruby-on-rails - 将 url_for 与 ActiveModel 实例一起使用时如何添加参数?
- jquery - FullCalendar 如何检测列表视图中的最后一行事件
- python - Python OPC UA 客户端安全策略(基本 256sha256)?
- android - java.lang.SecurityException:需要 MODIFY_PHONE_STATE 权限。是否可以以编程方式启用权限?
- django - DRF 指定所需的标题
- apache - Apache VirtualHost 重定向,仅更改域