Looping through JSON with node.js

2019-01-16 23:25发布

I have a JSON file which I need to iterate over, as shown below...

{
    "device_id": "8020",
    "data": [{
        "Timestamp": "04-29-11 05:22:39 pm",
        "Start_Value":  0.02,
        "Abstract": 18.60,
        "Editor": 65.20
    }, {
        "Timestamp": "04-29-11 04:22:39 pm",
        "End_Value":  22.22,
        "Text": 8.65,
        "Common": 1.10,
        "Editable": "true",
        "Insert": 6.0
    }]
}

The keys in data will not always be the same (i've just used examples, there are 20 different keys), and as such, I cannot set up my script to statically reference them to get the values.

Otherwise I could state

var value1 = json.data.Timestamp;
var value2 = json.data.Start_Value;
var value3 = json.data.Abstract;
etc

In the past i've used a simple foreach loop on the data node...

foreach ($json->data as $key => $val) {
    switch($key) {
        case 'Timestamp':
            //do this;
        case: 'Start_Value':
            //do this
    }
}

But don't want to block the script. Any ideas?

8条回答
该账号已被封号
2楼-- · 2019-01-16 23:50

You can iterate through JavaScript objects this way:

for(var attributename in myobject){
    console.log(attributename+": "+myobject[attributename]);
}

myobject could be your json.data

查看更多
smile是对你的礼貌
3楼-- · 2019-01-16 23:53

If you want to avoid blocking, which is only necessary for very large loops, then wrap the contents of your loop in a function called like this: process.nextTick(function(){<contents of loop>}), which will defer execution until the next tick, giving an opportunity for pending calls from other asynchronous functions to be processed.

查看更多
登录 后发表回答