JavaScript Object VS JSON

Javascript object Vs JSON


  1. Is the key/property name valid both with/without quotes ?

The only time you need to enclose a key in quotes when using Object Literal notation is where the key is a reserved word or contains a special character (if, :, - etc). It is worth noting that a key in JSON must be enclosed in double quotes.



  1. If I convert the above object to JSON using var jSonString = JSON.stringify(testObject);, what is the difference between the 2 (JS obj and JSON)?

JSON is a data interchange format. It's a standard which describes how ordered lists and unordered maps, strings, booleans and numbers can be represented in a string. Just like XML and YAML is a way to pass structured information between languages, JSON is the same. A JavaScript object on the other hand is a physical type. Just like a PHP array, a C++ class/ struct, a JavaScript object is a type internal to JavaScript.

Here's a story. Let's imagine you've purchased some furniture from a store, and you want it delivered. However the only one left in stock is the display model, but you agree to buy it.

In the shop, the chest-of-drawers you've purchased is a living object:

    var chestOfDrawers = {
color: "red",
numberOfDrawers: 4
}

However, you can't send a chest-of-drawers in the post, so you dismantle it (read, stringify it). It's now useless in terms of furniture. It is now JSON. Its in flat pack form.

    {"color":"red","numberOfDrawers":4}

When you receive it, you then rebuild the chest-of-drawers (read, parse it). Its now back in object form.

The reason behind JSON, XML and YAML is to enable data to be transferred between programming languages in a format both participating languages can understand; you can't give PHP or C++ your JavaScript object directly; because each language represents an object differently under-the-hood. However, because we've stringified the object into JSON notation; i.e. a standardised way to represent data, we can transmit the JSON representation of the object to another language (C++, PHP), they can recreate the JavaScript object we had into their own object based on the JSON representation of the object.

It is important to note that JSON cannot represent functions or dates. If you attempt to stringify an object with a function member, the function will be omitted from the JSON representation. A date will be converted to a string;

    JSON.stringify({
foo: new Date(),
blah: function () {
alert('hello');
}
}); // returns the string "{"foo":"2011-11-28T10:21:33.939Z"}"


  1. For parsing a JSON string, is the method below recommended? var javascriptObj = JSON.parse(jSonString);

Yes, but older browsers don't support JSON natively (IE <8). To support these, you should include json2.js.

If you're using jQuery, you can call jQuery.parseJSON(), which will use JSON.parse() under the hood if it's supported and will otherwise fallback to a custom implementation to parse the input.

What are the differences between JSON and JavaScript object?

First you should know what JSON is:

  • It is language agnostic data-interchange format.

The syntax of JSON was inspired by the JavaScript Object Literal notation, but there are differences between them.

For example, in JSON all keys must be quoted, while in object literals this is not necessary:

// JSON:
{ "foo": "bar" }

// Object literal:
var o = { foo: "bar" };

The quotes are mandatory on JSON because in JavaScript (more exactly in ECMAScript 3rd. Edition), the usage of reserved words as property names is disallowed, for example:

var o = { if: "foo" }; // SyntaxError in ES3

While, using a string literal as a property name (quoting the property name) gives no problems:

var o = { "if": "foo" }; 

So for "compatibility" (and easy eval'ing maybe?) the quotes are mandatory.

The data types in JSON are also restricted to the following values:

  • string
  • number
  • object
  • array
  • A literal as:

    • true
    • false
    • null

The grammar of Strings changes. They have to be delimited by double quotes, while in JavaScript, you can use single or double quotes interchangeably.

// Invalid JSON:
{ "foo": 'bar' }

The accepted JSON grammar of Numbers also changes, in JavaScript you can use Hexadecimal Literals, for example 0xFF, or (the infamous) Octal Literals e.g. 010. In JSON you can use only Decimal Literals.

// Invalid JSON:
{ "foo": 0xFF }

There are some buggy implementations (Firefox 3.5+, IE8+, json2.js) where octal literals are wrongly allowed, e.g. JSON.parse('01') should produce a SyntaxError.

What is the difference between JSON and Object Literal Notation?

Lets clarify first what JSON actually is. JSON is a textual, language-independent data-exchange format, much like XML, CSV or YAML.

Data can be stored in many ways, but if it should be stored in a text file and be readable by a computer, it needs to follow some structure. JSON is one of the many formats that define such a structure.

Such formats are typically language-independent, meaning they can be processed by Java, Python, JavaScript, PHP, you name it.

In contrast, JavaScript is a programming language. Of course JavaScript also provides a way to define/describe data, but the syntax is very specific to JavaScript.

As a counter example, Python has the concept of tuples, their syntax is (x, y). JavaScript doesn't have something like this.


Lets look at the syntactical differences between JSON and JavaScript object literals.

JSON has the following syntactical constraints:

  • Object keys must be strings (i.e. a character sequence enclosed in double quotes ").
  • The values can be either:

    • a string
    • a number
    • an (JSON) object
    • an array
    • true
    • false
    • null
  • Duplicate keys ({"foo":"bar","foo":"baz"}) produce undefined, implementation-specific results; the JSON specification specifically does not define their semantics

In JavaScript, object literals can have

  • String literals, number literals or identifier names as keys (since ES6, keys can now also be computed, which introduces yet another syntax).
  • The values can be any valid JavaScript expression, including function definitions and undefined.
  • Duplicate keys produce defined, specified results (in loose mode, the latter definition replaces the former; in strict mode, it's an error).

Knowing that, just by looking at the syntax, your example is not JSON because of two reasons:

  1. Your keys are not strings (literals). They are identifier names.
  2. You cannot assign a function as a value to a "JSON object" (because JSON doesn't define any syntax for functions).

But most importantly, to repeat my explanation from the beginning: You are in a JavaScript context. You define a JavaScript object. If any, a "JSON object" can only be contained in a string:

 var obj = {foo: 42}; // creates a JavaScript object (this is *not* JSON)
var json = '{"foo": 452}'; // creates a string containing JSON

That is, if you're writing JavaScript source code, and not dealing with a string, you're not dealing with JSON. Maybe you received the data as JSON (e.g., via ajax or reading from a file), but once you or a library you're using has parsed it, it's not JSON anymore.


Only because object literals and JSON look similar, it does not mean that you can name them interchangeably. See also There's no such thing as a "JSON Object".

javascript objects vs arrays vs JSON

JSON is a representation of the data structure, it's not an object or an array.

[1,2,3]

is an array.

{"foo":"bar"}

is an object.

In your example,

[
{"record_id":1,"name":"Frank"},
{"record_id":2,"name":"Sally"}
]

Is an array of objects.

{
"countries":
[
{"id":1,"name":"Canada"},
{"id":2,"name":"Mexico"}
],
"states":
[
{"id":1,"name":"Maine"},
{"id":2,"name":"Alaska"}
]
}

Is an object containing other arrays and objects inside of it.

What's the difference between Javascript Object and JSON object

A Javascript object is a data type in Javascript - it makes sense only in Javascript. Often you see a Javascript object literal like this:

var obj = {
a: 1,
b: 2
};

A JSON string is a data interchange format - it is nothing more than a bunch of characters formatted a particular way (in order for different programs to communicate with each other). Because of this, it can exist inside Javascript, or in another language or simply stored inside a database or a text file.

The above Javascript object can be represented in the JSON format in Javascript like this:

var json = '{ "a": 1, "b": 2 }';

Or in C# like this:

string json = "{ \"a\": 1, \"b\": 2 }";

As you can see, a JSON is simply stored inside a string. To make it useful, the JSON string can be parsed to produce an object in any language. Because the JSON format mimics Javascript's object literal syntax, Javascript makes the parsing process easy:

var obj = eval('(' + json + ')');

Though typically you'd see:

var obj = JSON.parse(json); // for security reasons

Note that JSON is limited in that it cannot store functions - the only values it can contain are:

  • objects (literals)
  • arrays
  • numbers
  • booleans
  • strings
  • nulls

exported Javascript object vs json file

Both ways work depending on a use case.

If you have a possibility to use local JSON or JS object as a configuration, without security issues, you can use local import without a problem.

If the data you want to import could be changed and should be retrieved on each page reload of your application or has some sensitive information, consider storing it at your backend server and retrieve it in any way(axios, AJAX, fetch, etc).

Performance of declaring json - JSON.parse vs object literal

There's no downside, JSON.parse returns an object just like the object literal gives you.

As for when to object literal or not read below.

As long as the JSON string is only evaluated once, the JSON.parse approach is much faster compared to the JavaScript object literal, especially for cold loads. A good rule of thumb is to apply this technique for objects of 10 kB or larger — but as always with performance advice, measure the actual impact before making any changes.

Source: https://v8.dev/blog/cost-of-javascript-2019



Related Topics



Leave a reply



Submit