How to grab data from JSON in CoffeeScript? [dupli

2019-01-29 14:42发布

问题:

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

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 }

How can I use CoffeeScript to:

  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?

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?

回答1:

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)