如何在CoffeeScript中从JSON抓取数据? [英] How to grab data from JSON in CoffeeScript?

查看:99
本文介绍了如何在CoffeeScript中从JSON抓取数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
如何使用CoffeeScript从JSON提取特定数据?

Possible Duplicate:
How to extract specific data from JSON using CoffeeScript?

我想从庞大的JSON字符串中获取特定的数据.如果在此处发布,则整个字符串的长度将超过10页,因此,我仅包含示例片段:

I want to grab a specific piece of data from a massive JSON string. The entire string would be more than 10 pages long if posted here, so I'm just including an example snippet:

   { name: '',
     keys:
      [ 'statType',
        'count',
        'dataVersion',
        'value',
        'championId',
        'futureData' ],
     object:
      { statType: 'TOTAL_SESSIONS_PLAYED',
        count: { value: 5 },
        dataVersion: 0,
        value: { value: 5 },
        championId: { value: 31 },
        futureData: null },
     encoding: 0 }

如何使用CoffeeScript进行以下操作:

How can I use CoffeeScript to:

  1. 解析该字符串以找到具有特定值(例如TOTAL_SESSIONS_PLAYED
  2. )的对象
  3. 从该对象(value字段)获取数值,然后
  4. 理想情况下,将该值附加到外部文本文件中吗?
  1. parse that string to locate the object with a specific value, such as TOTAL_SESSIONS_PLAYED,
  2. take the numerical value from that object (the value field), and
  3. ideally, append that value into an external text file?

我几乎是一个超级菜鸟程序员.基本上,在这个示例中,我如何才能从标有TOTAL_SESSIONS_PLAYED的对象中获取该5值,并使用CoffeeScript将其附加到文本文件中?

I am pretty much a super noob programmer. Basically, how could I, in this example, take that 5 value from the object labelled TOTAL_SESSIONS_PLAYED, and append it into a text file using CoffeeScript?

推荐答案

是否在节点中,您应该能够将JSON字符串传递给JSON.parse.并挑选出您想要的价值.然后,您可以使用Node的fs模块将文件追加到文件,如下所示: https://stackoverflow.com/a/11267583/659910.

Whether you're doing this in the browser or in Node, you should be able to pass the JSON string to JSON.parse and pick out the value you want. You can then append to a file using Node's fs module like this: https://stackoverflow.com/a/11267583/659910.

fs = require 'fs'

# Sample JSON string.
json = '{ "statType": "TOTAL_SESSIONS_PLAYED", "count": { "value": 5 }, "dataVersion": 0 }'

data = JSON.parse(json)
fs.appendFile('/tmp/data.txt', data.count.value, (error) -> throw error if error)

这篇关于如何在CoffeeScript中从JSON抓取数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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