How can I put JSON data into CoffeeScript?

27,066

If you want to create an array you can use myData = ['some info', 'some more info']

If you want to create an object you can use myData = {someKey: 'some value'}

Or you can use just myData = someKey: 'some value' (i.e. you can omit the {})

For more complicated object structures you use indentation with optional {} and optional commas, for example

myData =
    a: "a string"
    b: 0
    c:
        d: [1,2,3]
        e: ["another", "array"]
    f: false

will result in the variable myData containing an object with the following JSON representation, (which also happens to be valid CoffeeScript):

{
  "a": "a string",
  "b": 0,
  "c": {
    "d": [1, 2, 3],
    "e": ["another", "array"]
  },
  "f": false
}
Share:
27,066
Shamoon
Author by

Shamoon

Building products + communities with code. Entrepreneur with more losses than wins. Lifelong learner with a passion for AI+ML / #Bitcoin.

Updated on February 17, 2020

Comments

  • Shamoon
    Shamoon about 4 years

    Specifically, if I have some json:

    var myData = [ 'some info', 'some more info' ]
    var myOtherData = { someInfo: 'some more info' }
    

    What's the correct CoffeeScript syntax for that?

  • Trevor Burnham
    Trevor Burnham over 12 years
    Good overview. Just to clarify, almost all JSON or JavaScript object/array literals will work just fine when copy+pasted into CoffeeScript.