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

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

问题描述


可能重复:

我以前发过这个问题。没有人知道如何做到这一点

I posted this question before. Nobody knows how to do this?????????????????????

我想抓住一个特定的来自大量JSON字符串的数据。如果发布的整个字符串超过10页,因此我只包括一个示例代码片段:

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

 futureData: null },
     encoding: 0 },
   { 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 } ] },
dataVersion: 1, 

如何使用CoffeeScript ...

OK. How can I use CoffeeScript to...

1)解析特定字符串(如TOTAL_SESSIONS_PLAYED)的字符串。 2)从该对象取值(值字段)3)并且,最好将该值附加到一个外部文本文件中。

1) Parse that string for a specific string such as 'TOTAL_SESSIONS_PLAYED'. 2) Take the numerical value from that object (the value field) 3) And, ideally, append that value into an external text file.

我在这里疯了。请帮忙。谢谢!

I am going crazy here. Please help. Thanks!

编辑:我是一个超级noob程序员。基本上,在这个例子中,我怎么从标记为TOTAL_SESSIONS_PLAYED的对象中取5值,并使用CoffeeScript将它附加到文本文件中。

edit: 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模块附加到文件,如下所示: http://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: http://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天全站免登陆