Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

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 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.

share|improve this question

2 Answers

up vote 2 down vote accepted

How about this:

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

JSON.stringify(obj);
share|improve this answer
 
Thanks for answering so (very) fast, did the trick –  emiel187 Jul 16 at 10:25

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]

share|improve this answer
 
Parsing an array works for me too. Dunno what OP was doing. –  Amberlamps Jul 16 at 10:58

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.