使用 Node.js 循环 JSON

发布于 2024-11-03 20:53:56 字数 894 浏览 0 评论 0 原文

我有一个需要迭代的 JSON 文件,如下所示...

{
    "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
    }]
}

数据中的键并不总是相同的(我只是使用了示例,有 20 个不同的键),因此,我无法设置启动我的脚本以静态引用它们以获取值。

否则我可以说

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

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

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

但不想阻止脚本。有什么想法吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

燕归巢 2024-11-10 20:53:56

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

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

myobject 可以是您的 json.data

You can iterate through JavaScript objects this way:

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

myobject could be your json.data

洒一地阳光 2024-11-10 20:53:56

我建议利用 NodeJS 始终是 ES5 的事实。请记住,这不是浏览器,您可以依赖该语言的实现来保持稳定。也就是说,我建议不要在 NodeJS 中使用 for-in 循环,除非你真的想在原型链上进行深度递归。对于简单、传统的循环,我建议充分利用 ES5 中的 Object.keys 方法。如果您查看以下 JSPerf 测试,特别是如果您使用 Chrome(因为它具有相同的引擎(如 NodeJS),您将大致了解使用此方法比使用 for-in 循环性能提高多少(大约快 10 倍)。这是代码示例:

 var keys = Object.keys( obj );
 for( var i = 0,length = keys.length; i < length; i++ ) {
     obj[ keys[ i ] ];
 }

I would recommend taking advantage of the fact that nodeJS will always be ES5. Remember this isn't the browser folks you can depend on the language's implementation on being stable. That said I would recommend against ever using a for-in loop in nodeJS, unless you really want to do deep recursion up the prototype chain. For simple, traditional looping I would recommend making good use of Object.keys method, in ES5. If you view the following JSPerf test, especially if you use Chrome (since it has the same engine as nodeJS), you will get a rough idea of how much more performant using this method is than using a for-in loop (roughly 10 times faster). Here's a sample of the code:

 var keys = Object.keys( obj );
 for( var i = 0,length = keys.length; i < length; i++ ) {
     obj[ keys[ i ] ];
 }
拥有 2024-11-10 20:53:56

您可能还想在循环中使用 hasOwnProperty

for (var prop in obj) {
    if (obj.hasOwnProperty(prop)) {
        switch (prop) {
            // obj[prop] has the value
        }
    }
}

node.js 是单线程的,这意味着无论您是否愿意,您的脚本都会阻塞。还记得 V8(node.js 使用的 Google Javascript 引擎)将 Javascript 编译为机器代码,这意味着大多数基本操作都非常快,并且循环遍历具有 100 个键的对象可能需要几纳秒?

但是,如果您在循环内执行了更多操作,并且不希望它立即阻塞,则可以执行以下操作:

switch (prop) {
    case 'Timestamp':
        setTimeout(function() { ... }, 5);
        break;
    case 'Start_Value':
        setTimeout(function() { ... }, 10);
        break;
}

如果您的循环正在执行一些 CPU 密集型工作,则需要生成一个子进程来完成这项工作或使用网络工作者

You may also want to use hasOwnProperty in the loop.

for (var prop in obj) {
    if (obj.hasOwnProperty(prop)) {
        switch (prop) {
            // obj[prop] has the value
        }
    }
}

node.js is single-threaded which means your script will block whether you want it or not. Remember that V8 (Google's Javascript engine that node.js uses) compiles Javascript into machine code which means that most basic operations are really fast and looping through an object with 100 keys would probably take a couple of nanoseconds?

However, if you do a lot more inside the loop and you don't want it to block right now, you could do something like this

switch (prop) {
    case 'Timestamp':
        setTimeout(function() { ... }, 5);
        break;
    case 'Start_Value':
        setTimeout(function() { ... }, 10);
        break;
}

If your loop is doing some very CPU intensive work, you will need to spawn a child process to do that work or use web workers.

三生池水覆流年 2024-11-10 20:53:56

我最喜欢的方式是,

var objectKeysArray = Object.keys(yourJsonObj)
objectKeysArray.forEach(function(objKey) {
    var objValue = yourJsonObj[objKey]
})

My most preferred way is,

var objectKeysArray = Object.keys(yourJsonObj)
objectKeysArray.forEach(function(objKey) {
    var objValue = yourJsonObj[objKey]
})
情场扛把子 2024-11-10 20:53:56

如果您想避免阻塞(这仅对非常大的循环来说是必要的),请将循环的内容包装在一个如下所示的函数中:process.nextTick(function(){<循环内容>})< /code>,这会将执行推迟到下一个时钟周期,从而为来自其他异步函数的待处理调用提供了处理的机会。

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.

潇烟暮雨 2024-11-10 20:53:56

如果我们使用nodeJS,我们绝对应该利用它提供的不同库。 underscoreJS 中的each()、map()、reduce() 等内置函数减少了我们的工作量。这是一个示例

    var _=require("underscore");
    var fs=require("fs");

    var jsonObject=JSON.parse(fs.readFileSync('YourJson.json', 'utf8'));


    _.map( jsonObject, function(content) {
        _.map(content,function(data){
           if(data.Timestamp)
              console.log(data.Timestamp)          
           })
      })

If we are using nodeJS, we should definitely take advantage of different libraries it provides. Inbuilt functions like each(), map(), reduce() and many more from underscoreJS reduces our efforts. Here's a sample

    var _=require("underscore");
    var fs=require("fs");

    var jsonObject=JSON.parse(fs.readFileSync('YourJson.json', 'utf8'));


    _.map( jsonObject, function(content) {
        _.map(content,function(data){
           if(data.Timestamp)
              console.log(data.Timestamp)          
           })
      })
素年丶 2024-11-10 20:53:56

有点晚了,但我相信下面给出了一些进一步的说明。

您也可以使用简单的循环来遍历 JSON 数组,例如:

for(var i = 0; i < jsonArray.length; i++)
{
    console.log(jsonArray[i].attributename);
}

如果您有一个 JSON 对象并且想要循环遍历其所有内部对象,那么您首先需要获取数组中的所有键并循环遍历键使用键名称检索对象,例如:

var keys = Object.keys(jsonObject);
for(var i = 0; i < keys.length; i++) 
{
    var key = keys[i];
    console.log(jsonObject.key.attributename);
}

A little late but I believe some further clarification is given below.

You can iterate through a JSON array with a simple loop as well, like:

for(var i = 0; i < jsonArray.length; i++)
{
    console.log(jsonArray[i].attributename);
}

If you have a JSON object and you want to loop through all of its inner objects, then you first need to get all the keys in an array and loop through the keys to retrieve objects using the key names, like:

var keys = Object.keys(jsonObject);
for(var i = 0; i < keys.length; i++) 
{
    var key = keys[i];
    console.log(jsonObject.key.attributename);
}
梦幻的味道 2024-11-10 20:53:56

不确定它是否有帮助,但看起来这里托管的节点中可能有一个用于异步迭代的库:

https://github.com/caolan/async

Async 是一个实用程序模块,它为使用异步 JavaScript 提供了简单、强大的功能。虽然最初设计是为了与 Node.js 一起使用,但它也可以直接在浏览器中使用。

Async 提供了大约 20 个函数,其中包括常见的“功能”函数(map、reduce、filter、forEach...)以及异步控制流的一些常见模式(并行、系列、瀑布...)。所有这些函数都假设您遵循 Node.js 约定,提供单个回调作为异步函数的最后一个参数。

Not sure if it helps, but it looks like there might be a library for async iteration in node hosted here:

https://github.com/caolan/async

Async is a utility module which provides straight-forward, powerful functions for working with asynchronous JavaScript. Although originally designed for use with node.js, it can also be used directly in the browser.

Async provides around 20 functions that include the usual 'functional' suspects (map, reduce, filter, forEach…) as well as some common patterns for asynchronous control flow (parallel, series, waterfall…). All these functions assume you follow the node.js convention of providing a single callback as the last argument of your async function.

等你爱我 2024-11-10 20:53:56

看看特拉弗斯。它将为您递归地遍历对象树,并且在每个节点上您都有许多可以访问的不同对象 - 当前节点的键、当前节点的值、当前节点的父节点、当前节点的完整键路径等。 https://github.com/substack/js-traverse。当我需要在转换各种数据位时进行深度克隆时,我使用它对想要清除循环引用的对象产生了良好的效果。下面是从他们的示例中提取的一些代码,让您了解它的功能。

var id = 54;
var callbacks = {};
var obj = { moo : function () {}, foo : [2,3,4, function () {}] };

var scrubbed = traverse(obj).map(function (x) {
    if (typeof x === 'function') {
        callbacks[id] = { id : id, f : x, path : this.path };
        this.update('[Function]');
        id++;
    }
});

console.dir(scrubbed);
console.dir(callbacks);

Take a look at Traverse. It will recursively walk an object tree for you and at every node you have a number of different objects you can access - key of current node, value of current node, parent of current node, full key path of current node, etc. https://github.com/substack/js-traverse. I've used it to good effect on objects that I wanted to scrub circular references to and when I need to do a deep clone while transforming various data bits. Here's some code pulled form their samples to give you a flavor of what it can do.

var id = 54;
var callbacks = {};
var obj = { moo : function () {}, foo : [2,3,4, function () {}] };

var scrubbed = traverse(obj).map(function (x) {
    if (typeof x === 'function') {
        callbacks[id] = { id : id, f : x, path : this.path };
        this.update('[Function]');
        id++;
    }
});

console.dir(scrubbed);
console.dir(callbacks);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文