Node.js – parsing简单的JSON对象和访问键和值

我是Node新手,并努力访问一个简单的JSON对象。 我的request.body将具有类似于以下的JSON内容:

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

“store_config”值将始终存在,但其中的键和值可以是任何值。

我如何迭代通过键和值访问每个? 我也想以asynchronous的方式处理每一个。

欣赏任何想法或方向。


UPDATE

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

返回: Object

 parsedBody = JSON.parse(request.body); 

收益:

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

更新2 – 进一步debugging:

当我尝试遍历数组时,只有一个值:

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

收益:

 0 { name: 'hello', name2: 'world' } 

如果request.body已经被parsing为JSON,那么您可以将数据作为JavaScript对象来访问; 例如,

 request.body.store_config 

否则,您将需要使用JSON.parseparsing它:

 parsedBody = JSON.parse(request.body); 

由于store_config是一个数组,您可以遍历它:

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

如果您需要对数组中的每个项目执行asynchronous处理,并且需要知道何时完成,那么我build议您查看asynchronous助手库( 如async) – 特别是, async.forEach可能对您有用 :

 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 }); 

在此屏幕录像中,我将谈一点关于asynchronous库的asynchronous处理。

像这样的东西:

 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]); } } 

为了将这个sting转换成实际的对象,使用JSON.parse 。 你可以迭代Javascript对象,就像使用数组一样。

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