2

How convert JSON to CoffeeScript and write on a file ".coffee" with NodeJS?

JSON:

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

to CoffeeScript:

"name": "jack"
"type": 1
Kijewski
  • 25,517
  • 12
  • 101
  • 143
Fuechter
  • 1,200
  • 2
  • 10
  • 27
  • 2
    Why would you want to do that?! – Naftali Sep 23 '13 at 15:30
  • 1
    Huge fan of coffeescript and I agree with Neal, there's no good reason to do this. JSON in "js" form is entirely compatible with coffeescript. If you want to reshape the object then that is a different question. – jcollum Sep 23 '13 at 17:17

2 Answers2

2

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/

Community
  • 1
  • 1
Kijewski
  • 25,517
  • 12
  • 101
  • 143
-4

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:

https://github.com/rstacruz/js2coffee

mkoryak
  • 57,086
  • 61
  • 201
  • 257