How convert JSON to CoffeeScript and write on a file ".coffee" with NodeJS?
JSON:
{
"name": "jack",
"type": 1
}
to CoffeeScript:
"name": "jack"
"type": 1
How convert JSON to CoffeeScript and write on a file ".coffee" with NodeJS?
JSON:
{
"name": "jack",
"type": 1
}
to CoffeeScript:
"name": "jack"
"type": 1
Should be easy enough by traversing the object (for … of
). Just use recursion and take the indent level as an argument:
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'
Test case:
alert csonify
brother:
name: "Max"
age: 11
toys: [
"Lego"
"PSP"
]
sister:
name: "Ida"
age: 9
Result:
"brother":
"name":
"Max"
"age":
11
"toys":
[
"Lego"
"PSP"
]
"sister":
"name":
"Ida"
"age":
9
No live demo, since I don't know a JSFiddle for CoffeScript.
Live demo: http://jsfiddle.net/vtX3p/
I hope you know how to read and write files in nodejs, so i will not address that here. To convert javascript to coffeescript you can use this npm: