将字符串转换为JSON对象数组(Node.js) [英] Convert String to Array of JSON Objects (Node.js)

查看:841
本文介绍了将字符串转换为JSON对象数组(Node.js)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我得到了:

var obj = {
        "title": request.param('title'),
        "thumb": request.param('thumb'),
        "items": request.param('items')
    };

和request.param('items')包含对象数组,但仍为字符串:

and request.param('items') contains an array of object but still as a string:

'[{"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"}]
        };

代替

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

有人可以帮助我吗? JSON.parse不会解析对象数组,而只会解析有效的JSON.

Anyone who can help me with this? JSON.parse doesn't parse an array of object, only valid JSON.

推荐答案

这是怎么回事:

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

JSON.stringify(obj);

这篇关于将字符串转换为JSON对象数组(Node.js)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆