localStorage - 1

So, there is a weird difference between an “object” and a “JSON object”.

Because really, strictly speaking, “JSON” is not an object at all, it’s a string.

It’s a string that happens to contain content in a syntax which represents an object. Or whatever else you want to save as JSON.

Let me explain what I mean.

// this is some Javascript that you can paste into your console.
let word = { "form" : "casa", "gloss": "house"}
// that’s an object. You can even ask Javascript what type `word` is, and it
// will tell you that it’s an object:
typeof word
// but, watch this:
let jsonString = JSON.stringify(word) // no seriously, it’s called “stringify”.
typeof jsonString
// a string.

So word is a Javascript object, but jsonString is a string that represents that object!

You can go the other way too:

let wordAgain = JSON.parse(jsonString)
typeof wordAgain // object

Here’s something a little mind-bendy:

console.log(jsonString)

That looks more or less like an object, except curiously, there is no syntax highlighting. Why? Because there’s nothing to highlight: there are no variables and brackets and whatever, there’s just a string that happens to contain content which is JSON.

It gets weirder. What if you don’t call console.log(jsonString), but rather, just say “Hey Javascript, what do you think jsonString is?”

  jsonString // (just try typing this and hitting enter)

It will show you this:

  "{\"form\":\"casa\",\"gloss\":\"house\"}"

🤔

Well, it’s a string alright, as it’s wrapped in quotes like "any other string". But the quotes which are inside the JSON string are \escaped.

That escaping business is a thing in programming in general. Because, if you have a character that has a special meaning, like, a " means “the beginning or the end of a string,”, well then, how do you put a quote inside your string? You have to escape it. In JSON (and Javascript), the way you do that is to precede it with a “backslash”: \.

But this is where things get even weirder.

If you want to put some JSON into a file, you might think you should escape quotes — after all, a file is just a string stuck on a hard drive, right? And yet, you don’t.

Here’s the “railroad diagram” that shows the definition of strings in the

Syntax of strings in JSON (json.org)

Okay. part 2.