修改Coffeescript中的JSON文件

时间:2013-06-27 18:40:56

标签: javascript json parsing coffeescript

我不确定如何使用coffee脚本修改JSON文件格式 我有类似的东西

{"counts":{"USA":100,"France":90,"Italy":80,"Canada":70,"Germany":60}}

我想将json转换为此

[{text: "USA", weight: 100},{text: "France", weight: 90},{text: "Italy",weight: 80},{text: "Canada", weight: 70}, {text: "Germany", weight: 60}]

这在Java中很容易,但对咖啡脚本不太确定

1 个答案:

答案 0 :(得分:1)

我将使用的CoffeeScript功能:

  • 数组理解(for循环的返回值)
  • for key, value of object循环
  • object literal comisition shorthard { foo }{ foo: foo }
  • 相同

示例:

data = {"counts":{"USA":100,"France":90,"Italy":80,"Canada":70,"Germany":60}}

result =
  for text, weight of data.counts
    { text, weight }

console.log result
# [{"text":"USA","weight":100},{"text":"France","weight":90},{"text":"Italy","weight":80},{"text":"Canada","weight":70},{"text":"Germany","weight":60}]