🏠 back to Observable

Is there no way to write raw JSON?


#1

I have an API response that is well-formatted, but if I copy and paste it into Observable I get complaints about syntax. If I manually update the keys to not have quotes, I still get complaints about syntax. I can’t seem to write literal objects in any observable (https://beta.observablehq.com/d/6b4dacff8d4bb988)

I don’t want to hit this API at the moment. I suppose (temporarily) I could put the response in a Github Gist and call it, but I want this literal object problem solved! What do I need to do differently?


#2

An addendum to my question: I can write JSON in a cell in this fashion:

{
    const json = {
        'key': 'item'
   }
   return json
}

Could someone explain to me what this unusual syntax is? Why is there this added level to get to the declaration of a literal object?


#3

Cells are akin to the bodies of arrow functions, so you need parentheses to disambiguate an object literal from a block statement. Try this:

({
  key: "item"
})

Or to name it:

object = ({
  key: "item"
})

Of course, if you want to parse JSON and not use an Object literal (since JSON is not a true subset of JavaScript), you’ll need JSON.parse:

object = JSON.parse(`{
  "key": "item"
}`)

For more on cell syntax, see the Introduction to Code: