Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/417.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将字符串转换为JSON对象数组(Node.js)_Javascript_Json_Node.js_Express - Fatal编程技术网

Javascript 将字符串转换为JSON对象数组(Node.js)

Javascript 将字符串转换为JSON对象数组(Node.js),javascript,json,node.js,express,Javascript,Json,Node.js,Express,我正在使用Node.js和express(3.x)。我必须为mac客户端提供API,并从post请求中提取正确的字段。(必须使用request.param),但字段应重新组合为JSON,而不是字符串 我得到: var obj = { "title": request.param('title'), "thumb": request.param('thumb'), "items": request.param('items') }; 和re

我正在使用Node.js和express(3.x)。我必须为mac客户端提供API,并从post请求中提取正确的字段。(必须使用request.param),但字段应重新组合为JSON,而不是字符串

我得到:

var obj = {
        "title": request.param('title'),
        "thumb": request.param('thumb'),
        "items": request.param('items')
    };
和request.param('items')包含一个对象数组,但仍然是一个字符串:

'[{"name":"this"},{"name":"that"}]'
我想附加它,使其成为:

var obj = {
            "title": request.param('title'),
            "thumb": request.param('thumb'),
            "items": [{"name":"this"},{"name":"that"}]
        };
而不是

var obj = {
                "title": request.param('title'),
                "thumb": request.param('thumb'),
                "items": "[{\"name\":\"this\"},{\"name\":\"that\"}]"
            };
有人能帮我吗?JSON.parse不解析对象数组,只解析有效的JSON。

这样如何:

var obj = JSON.parse("{\"items\":" + request.param('items') + "}");
obj.title = request.param('title');
obj.thumb = request.param('thumb');

JSON.stringify(obj);

也许我遗漏了什么,但这很好:

> a = '[{"name":"this"},{"name":"that"}]';
'[{"name":"this"},{"name":"that"}]'
> JSON.parse(a)
[ { name: 'this' }, { name: 'that' } ]

Node@0.10.13

可能您有旧的库原型。当我移除它时,bug已经消失了

您可以尝试相同的代码。一旦进入Prototype.js页面。第二次在没有库的新页面中