admin管理员组

文章数量:1236540

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 posed back together to JSON, instead of strings.

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:

'[{"name":"this"},{"name":"that"}]'

I want to append it so it bees:

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.

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 posed back together to JSON, instead of strings.

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:

'[{"name":"this"},{"name":"that"}]'

I want to append it so it bees:

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.

Share Improve this question asked Jul 16, 2013 at 10:07 emiel187emiel187 1912 gold badges3 silver badges9 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 7

How about this:

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

JSON.stringify(obj);

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' } ]

[email protected]

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.

本文标签: javascriptConvert String to Array of JSON Objects (Nodejs)Stack Overflow