10

I am new to Node and struggling to access a simple JSON object. My request.body will have JSON content similar to the following:

{
    "store_config": [
        {
            "name": "hello",
            "name2": "world"
        }
    ]
}

The "store_config" value will always be present, however the keys and values within could be anything.

How can I iterate through the keys and values to access each? I would also like to process each in an asynchronous manner.

Appreciate any thoughts or direction.


UPDATE

console.log(typeof(request.body));

Returns: Object

parsedBody = JSON.parse(request.body);

returns:

SyntaxError: Unexpected token o
    at Object.parse (native)

UPDATE 2 - Further debug:

When I try to iterate through the array, there is only a single value:

request.body.store_config.forEach(function(item, index) {
  console.log(index);
  console.log(request.body.store_config[index]);

});

returns:

0
{ name: 'hello', name2: 'world' }
2
  • "I would also like to process each in an asynchronous manner." Uhm... why? Commented Nov 11, 2012 at 18:06
  • FYI, node runs in single thread, so the asynchronous is not the same as in multi-threading programming. When you make a async call with native async procedure like fs.*, it will register a event handler to the event-loop to wait for job to be done. In other cases, you just register a event handler to process.nextTick event, which will callback at each tick, and your code run in series not parallel. Commented Nov 11, 2012 at 18:19

3 Answers 3

18

If request.body is already being parsed as JSON, you can just access the data as a JavaScript object; for example,

request.body.store_config

Otherwise, you'll need to parse it with JSON.parse:

parsedBody = JSON.parse(request.body);

Since store_config is an array, you can iterate over it:

request.body.store_config.forEach(function(item, index) {
  // `item` is the next item in the array
  // `index` is the numeric position in the array, e.g. `array[index] == item`
});

If you need to do asynchronous processing on each item in the array, and need to know when it's done, I recommend you take a look at an async helper library like async--in particular, async.forEach may be useful for you:

async.forEach(request.body.store_config, function(item, callback) {
  someAsyncFunction(item, callback);
}, function(err){
  // if any of the async callbacks produced an error, err would equal that error
});

I talk a little bit about asynchronous processing with the async library in this screencast.

Sign up to request clarification or add additional context in comments.

7 Comments

This only applies when using connect/express with bodyParser.
@brandon-tilley Many thanks. How can I confirm if my request.body is being parsed as JSON already? If I output the store_config, it is an object: console.log(typeof(request.body.store_config)); console.log(request.body.store_config); object [ { name: 'hello', name2: 'world' } ]
If it's "object," then it has been parsed--parsing turns a string into an object. (If it was a string, trying to do request.body.store_config would give an error.)
When I try to iterate through the array, there is only a single value: request.body.store_config.forEach(function(item, index) { console.log(index); console.log(request.body.store_config[index]); }); returns - 0 { name: 'hello', name2: 'world' }
@Ben: That seems correct, as you have one item in your example -- one object with the two properties name and name2.
|
2

Something like this:

config = JSON.parse(jsonString);
for(var i = 0; i < config.store_config.length; ++i) {
   for(key in config.store_config[i]) {
      yourAsyncFunction.call(this, key, config.store_config[i][key]);
   }
}

Comments

-1

To convert this sting to an actual object, use JSON.parse. You can iterate though Javascript objects like you would with an array.

config = JSON.parse(string).store_config[0]
foreach (var key in config) {
    value = config[key]
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.