将字符串转换为 JSON 对象数组 (Node.js)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17673702/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert String to Array of JSON Objects (Node.js)
提问by emiel187
I'm using Node.js and express (3.x). I have to provide an API for a mac client and from a post request I extract the correct fields. (The use of request.param is mandatory) But the fields should be composed back together to JSON, instead of strings.
我正在使用 Node.js 和 express (3.x)。我必须为 mac 客户端提供 API,并从发布请求中提取正确的字段。( request.param 的使用是强制性的)但是这些字段应该重新组合成 JSON,而不是字符串。
I got:
我有:
var obj = {
"title": request.param('title'),
"thumb": request.param('thumb'),
"items": request.param('items')
};
and request.param('items') contains an array of object but still as a string:
和 request.param('items') 包含一个对象数组,但仍然是一个字符串:
'[{"name":"this"},{"name":"that"}]'
I want to append it so it becomes:
我想附加它,使它成为:
var obj = {
"title": request.param('title'),
"thumb": request.param('thumb'),
"items": [{"name":"this"},{"name":"that"}]
};
Instead of
代替
var obj = {
"title": request.param('title'),
"thumb": request.param('thumb'),
"items": "[{\"name\":\"this\"},{\"name\":\"that\"}]"
};
Anyone who can help me with this? JSON.parse doesn't parse an array of object, only valid JSON.
谁能帮我解决这个问题?JSON.parse 不解析对象数组,只解析有效的 JSON。
回答by Amberlamps
How about this:
这个怎么样:
var obj = JSON.parse("{\"items\":" + request.param('items') + "}");
obj.title = request.param('title');
obj.thumb = request.param('thumb');
JSON.stringify(obj);
回答by robertklep
Perhaps I'm missing something, but this works just fine:
也许我错过了一些东西,但这很好用:
> a = '[{"name":"this"},{"name":"that"}]';
'[{"name":"this"},{"name":"that"}]'
> JSON.parse(a)
[ { name: 'this' }, { name: 'that' } ]
节点@0.10.13
回答by Thibaut
May be you have old library Prototype. As I remove it, bug has disappeared.
可能是你有旧的图书馆原型。当我删除它时,错误消失了。
You can try the same code. Once in page with Prototype.js. Second time in new page without library.
您可以尝试相同的代码。使用 Prototype.js 进入页面后。第二次在没有库的新页面中。

