Reputation: 61
I'm wondering what the advantages of storing data as JSON are compared to just storing it as JavaScript objects. For example, if I have a file with the following JSON:
{
"pizza": [
{
"name": "Margherita",
"price": 65,
"ingredients": [
"tomatsås",
"mozzarella",
"basilika"
]
},
{
"name": "Pizza ai quattro formaggi",
"price": 70,
"ingredients": [
"tomatsås",
"mozzarella",
"gorgonzola",
"parmesan",
"fontina"
]
}
]
}
why can't I just write it as a JavaScript object like this:
menu = {
pizza: [
{
name: "Margherita",
price: 65,
ingredients: [
"tomatsås",
"mozzarella",
"basilika"
]
},
{
name: "Pizza ai quattro formaggi",
price: 70,
ingredients: [
"tomatsås",
"mozzarella",
"gorgonzola",
"parmesan",
"fontina"
]
}
]
}
that way I don't have to parse it, it's easier to access if the file is stored locally, and it's even slightly shorter since the keys don't need to be in quotes.
However, since this is my first time using JSON I'm probably missing something, so what are the benefits of using JSON over a JavaScript object?
Upvotes: 6
Views: 2618
Reputation: 163272
They're tools for different jobs. JSON is a data serialization format. JavaScript (which is what your standard inline objects must be in) is for writing your scripts.
This has implications in how you can use them. For example, you can't (easily) have a script that creates JavaScript with an inline object. Suppose you wanted to write out this data as JSON with your script. It's as simple as writeFile('file', JSON.stringify(data))
. There is no built-in library for creating JavaScript with JavaScript, so you couldn't write a JavaScript script with an object directly. At best, you could concatenate a static script (const menu =
in your case) to the JSON-encoded data.
There are potential security implications as well. Nothing stored in your JSON blob will be executed, ever. However if you make a mistake when building this script with arbitrary data, there is a potential to execute something since the script has to be executed to be evaluated.
Without using a loader, your script can only work in a specific context. That is, if it has const menu =
at the top, menu
is declared and cannot be renamed/reused without some workarounds. With loading the JSON, you can parse it and use it however you want, in whatever context you want, without worrying about side effects.
that way I don't have to parse it
The JavaScript compiler does.
it's easier to access if the file is stored locally
I assume you're referring to loading files directly on disk. It's recommended that you run a small basic web server.
and it's even slightly shorter since the keys don't need to be in quotes
This isn't really a winning argument either way. The difference is marginal.
I suspect that the JSON parser will be marginally faster as well, since it has less to deal with.
Upvotes: 2