DEV Community

KenjiGoh
KenjiGoh

Posted on

2

JSON vs JavaScript Object Literal

What is Js Object Literal?

The standard definition would be: it is a comma-separated list of name-value pairs wrapped in curly braces. You can think of it as a 'container' for datas, for example:

const myObject = {
    stringProp: 'value',
    numberProp: 2,
    booleanProp: false,
    arrayProp: ["hello.jpg","smile.png"],
    positionProp: {
        x: 40,
        y: 200
   },
   someAction: function(){
      //action logics
   }
};
Enter fullscreen mode Exit fullscreen mode

What is JSON?

JSON stands for JavaScript Object Notation, which is a lightweight format for storing and transporting of data. Data is usually fetched from a server to the browser in this format. The syntax looks very similar to Js Objects.

In JSON format:

{
    "firstName":"John",
    "lastName":"Doe"
}
Enter fullscreen mode Exit fullscreen mode

In JavaScript Object:

const person = {
    firstName:"John",
    lastName:"Doe"
}
Enter fullscreen mode Exit fullscreen mode

Comparing to a JavaScript Object, the not-so-obvious difference is that both the name and value are doubled-quoted in JSON but only the value is doubled-quoted in Js Object.

Conversion

JavaScript has built-in support to convert between JSON and Js Object.

To convert an Object to JSON Data:

JSON.stringify(Object)
Enter fullscreen mode Exit fullscreen mode

To convert a JSON data to an Object:

JSON.parse(data)
Enter fullscreen mode Exit fullscreen mode

JavaScript Object will be displayed as the following on browser, thus the need to be converted to JSON.

[object Object]
Enter fullscreen mode Exit fullscreen mode

For React users, sometimes we will forget to convert an Object to JSON and will often see this error message when we try to render it:
Error Msg

That's all! Thanks for reading my short post.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay