In JavaScript, you can create/declare a JSON object as a JavaScript object literal. A JavaScript object literal is a comma-separated list of key-value pairs enclosed in curly braces {}
.
Here is an example of a JSON object declared as a JavaScript object literal:
let person = {
"name": "John",
"age": 30,
"city": "New York"
};
You can also declare an empty JSON object like this:
let emptyObj = {};
Or you can initialize a JSON object with properties later like this:
let person = {};
person.name = "John";
person.age = 30;
person.city = "New York";
JavaScript creates JSON object example
A simple example code can create a JSON object by using the JSON.stringify()
method to convert a JavaScript object into a JSON string.
<!DOCTYPE html>
<html>
<body>
<script>
let person = {
"name": "John",
"age": 30,
"city": "New York"
};
console.log(person)
let personJSON = JSON.stringify(person);
console.log(personJSON)
</script>
</body>
</html>
Output:
Do comment if you have any doubts or suggestions on this JS JSON topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version