2013-09-23 57 views
1

如何将JSON转换为CoffeeScript并使用NodeJS在文件“.coffee”上写入?如何将JSON转换为CoffeeScript并写入文件“.coffee”?

JSON:

{ 
    "name": "jack", 
    "type": 1 
} 

到的CoffeeScript:

"name": "jack" 
"type": 1 
+2

为什么你要这么做? – Neal

+1

coffeescript的巨大粉丝,我同意尼尔,没有很好的理由这样做。 JSON格式的JSON与coffeescript完全兼容。如果你想重塑对象,那么这是一个不同的问题。 – jcollum

回答

2

应该是通过遍历对象(for … of)很容易。只需使用递归,并采取缩进级别作为参数:

esc_string = (s) -> 
    return '"' + s.replace(/[\\"]/g, '\\$1') + '"' 

csonify = (obj, indent) -> 
    indent = if indent then indent + 1 else 1 
    prefix = Array(indent).join "\t" 
    return prefix + esc_string obj if typeof obj is 'string' 
    return prefix + obj if typeof obj isnt 'object' 
    return prefix + '[\n' + (csonify(value, indent) for value in obj).join('\n') + '\n' + prefix + ']' if Array.isArray obj 
    return (prefix + esc_string(key) + ':\n' + csonify(value, indent) for key, value of obj).join '\n' 

测试用例:

alert csonify 
    brother: 
    name: "Max" 
    age: 11 
    toys: [ 
     "Lego" 
     "PSP" 
    ] 
    sister: 
    name: "Ida" 
    age: 9 

结果:

"brother": 
    "name": 
     "Max" 
    "age": 
     11 
    "toys": 
     [ 
      "Lego" 
      "PSP" 
     ] 
"sister": 
    "name": 
     "Ida" 
    "age": 
     9 

没有现场演示,因为我不知道一个CoffeScript的JSFiddle。

现场演示:http://jsfiddle.net/vtX3p/

+1

http://jsfiddle.net/,在语言下,你可以改变JS,咖啡:) – Val