Node.js - Parse simple JSON object and access keys and values
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.
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]); }}
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]}