{
"name": "Alice",
"age": 30,
}
[23, 21, 33, "Alice", "Bob", true]
const obj = {"name": "Alice"};
const name = obj["name"]; // using string index notation
const name = obj.name; // using the key directly
const variableKey = "dynamicKey";
const value = obj[variableKey];
let obj = { };
console.log(obj.key1.key2); // Cannot read properties of undefined (reading 'key2')
Solutuon 1: make sure to check if the variable is defined before accessing its properties.console.log(obj && obj.key1 && obj.key1.key2); // undefined (no error)
Solutuon 2: use libraries like lodash or underscore:import _ from 'lodash'; // or using 'underscore'
console.log(_.get(obj, 'key1.key2')); // undefined (no error)
Solutuon 3: use optional chaining operator:console.log(obj?.key1?.key2); // undefined (no error)
obj && obj.key1 && obj.key1.key2
approach has broad browser support and minimal bundle size impact but may be slightly more verbose.for...in
loop to iterate through the object's properties.const jsonObj = {
name: 'John',
age: 30,
city: 'New York'
};
for (let key in jsonObj) {
const value = jsonObj[key];
console.log(key, value);
}
_.forEach(obj, function(value,key) {
console.log(key, value)
});
for
loop:const jsonArray = [
{ name: 'John', age: 30, city: 'New York' },
{ name: 'Alice', age: 25, city: 'Los Angeles' },
];
for (let index = 0; index < jsonArray.length; index++) {
const item = jsonArray[i];
console.log(index, item);
}
jsonArray.forEach((item, index) => {
console.log(index, item);
});
const obj = { "key1": 1 };
const variableKey = 'dynamicKey';
const obj = { [variableKey]: 1 };
const obj = { key1: 1 }; // existing object
obj.key2 = 2; // dot notation
obj['key3'] = 'value'; // square brackets
const obj = { "key1": 1 };
delete obj.key1;
const object1 = {"a": 1};
const object2 = {"b": 2};
const mergedObject = { ...object1, ...object2 }; // {"a": 1, "b": 2}
Data Interchange Between Browser and Server
JSON.stringify()
to convert object into string:const json = {
"name": "Alice",
"age": 30,
};
JSON.stringify(json); // returns string: '{"name":"Alice","age":30}'
JSON.stringify()
method for this task, there are situations where you might want to consider using specialized libraries like fast-safe-stringify, json-stringify-safe, and fast-json-stringify.fast-safe-stringify
and offer a safe way to serialize objects with circular references, ensuring application won't break.fast-json-stringify
focus on optimizing the serialization process for high performance. If you need fast serialization of large objects, this library may offer the high performance serialization.JSON.parse()
is the reverse process, where a JSON string is converted back into a data structure or object that can be used in a JavaScript.const str = '{"name":"Alice","age":30}';
JSON.parse(str); // returns json object: {"name":"Alice","age":30}
JSON.parse()
method to deserialize JSON string, there are some libraries like secure-json-parse and fast-json-parse could help you do it more efficient and safer.secure-json-parse
are designed with a focus on data security issue such as XSS.JSON.parse()
function, especially when the data is complex or wrong.secure-json-parse
make it easier to find and fix errors by offering more robust error handling mechanism.fast-json-parse
can make JSON parsing much faster. If you need to parse a lot of JSON data quickly, this library may be the best option for you.JSON Data in API Request
JSON Data in NPM package.json
BSON Data in mongodb
// Example using MongoDB and Node.js
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017'; // Database connection URL
MongoClient.connect(url, (err, client) => {
if (err) throw err;
const db = client.db('mydatabase'); // Use your database name
const collection = db.collection('userProfiles'); // Use your collection name
// JSON user profile data
const user1 = {
"username": "bob",
"age": 30,
"email": "bob@example.com",
};
const user2 = {
"username": "alice",
"age": 31,
};
// Insert the user profiles into the collection
collection.insertOne(user1);
collection.insertOne(user2);
});
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017'; // Database connection URL
MongoClient.connect(url, (err, client) => {
if (err) throw err;
const db = client.db('mydatabase'); // Use your database name
const collection = db.collection('articles'); // Use your collection name
// Example JSON data with unstructured and semi-structured content
const article1 = {
"title": "Introduction to NoSQL Databases",
"author": "John Doe",
"content": "NoSQL databases come in many varieties, each designed for specific use cases."
};
const article2 = {
"title": "Exploring JSON",
"author": "Jane Smith",
"content": "JSON is a popular format, known for its flexibility. See http://json-5.com"
};
const article3 = {
"title": "Web Development Best Practices",
"author": "Robert Johnson",
"content": "In modern web development, best practices emphasize security, scalability, and user experience.",
"tags": ["web development", "best practices", "security"]
};
// Insert articles into the collection
collection.insertMany([article1, article2, article3]);
// Query and retrieve articles by tag
collection.find({ tags: "web development" }).toArray((err, articles) => {
console.log(articles)
});
});
const express = require('express');
const { MongoClient } = require('mongodb');
const app = express();
const port = 3000; // Replace with your desired port
// MongoDB connection URL
const mongoUri = 'mongodb://localhost:27017';
// Connect to MongoDB
MongoClient.connect(mongoUri, { useUnifiedTopology: true })
.then(client => {
console.log('Connected to MongoDB');
const db = client.db('mydatabase'); // Use your database name
const collection = db.collection('data'); // Use your collection name
// Middleware for parsing JSON data in requests
app.use(express.json());
// Define a route to retrieve data from MongoDB
app.get('/api/data', async (req, res) => {
const data = await collection.find({}).toArray();
res.json(data);
});
app.listen(port, () => {
console.log("Server is running");
});
})
.catch(err => {
console.error('Error connecting to MongoDB:', err);
});