通过JSON循环使用的node.js [英] Looping through JSON with node.js

查看:314
本文介绍了通过JSON循环使用的node.js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我需要遍历一个JSON文件,如下图所示...

  {
    DEVICE_ID:8020,
    数据:[{
        时间戳:11年4月29日下午5时22分39秒,
        START_VALUE:0.02,
        摘要:18.60,
        编辑:65.20
    },{
        时间戳:11年4月29日下午4时22分39秒,
        END_VALUE:22.22,
        文本:8.65,
        共同:1.10,
        可编辑:​​真,
        插入:6.0
    }]
}

在数据的关键并不总是相同的(我刚刚使用的例子,有20个不同的密钥),正因为如此,我不能设置我的脚本来静态地引用它们得到的值。

否则我可以声明

  VAR值1 = json.data.Timestamp;
VAR值2 = json.data.Start_Value;
VAR值3 = json.data.Abstract;
等等

在过去,我用一个简单的foreach循环的数据节点上...

 的foreach($ json->数据作为$关键=> $ VAL){
    开关($键){
        案时间戳:
            //做这个;
        案例:START_VALUE:
            //做这个
    }
}

但不想阻止脚本。任何想法?


解决方案

您可以通过JavaScript对象迭代这种方式:

 为(以VAR为MyObject属性名){
    的console.log(属性名+:+ MyObject的[属性名]);
}

MyObject的可能是你的json.data

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?

解决方案

You can iterate through JavaScript objects this way:

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

myobject could be your json.data

这篇关于通过JSON循环使用的node.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆