Search code examples
jsoncoffeescript

How can I put JSON data into CoffeeScript?


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?


Solution

  • 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
    }