Introduction to LiveJSON
LiveJSON is a powerful JSON manipulation library that allows developers to interact with JSON data in a dynamic and real-time manner. The library boasts a rich set of APIs designed to make JSON processing smooth and efficient. From basic operations like reading and writing JSON data to advanced functionalities like schema validation and data transformation, LiveJSON has it all.
APIs and Code Examples
Initializing JSON Object
Initialize your JSON data using the init()
method:
const liveJson = require('livejson'); let data = liveJson.init({ "name": "John", "age": 30, "city": "New York" });
Accessing JSON Data
Retrieve data using the get()
method:
let name = data.get('name'); // returns John
Updating JSON Data
Update data with the set()
method:
data.set('age', 31);
Adding New Key-Value Pair
Use the add()
method to add new key-value pairs:
data.add('country', 'USA');
Deleting a Key-Value Pair
Delete data with the remove()
method:
data.remove('city');
Checking Key Presence
Check if a key exists using has()
:
let hasCity = data.has('city'); // returns false
Listing All Keys
List all keys using keys()
:
let keys = data.keys(); // returns ['name', 'age', 'country']
Converting to String
Convert JSON data to a string with toString()
:
let jsonString = data.toString();
Schema Validation
Validate JSON data with a schema using validateSchema()
:
let schema = { "type": "object", "properties": { "name": {"type": "string"}, "age": {"type": "number"} }, "required": ["name", "age"] }; let isValid = data.validateSchema(schema); // returns true
Transforming Data
Transform data with the transform()
method:
let transformedData = data.transform((jsonData) => { jsonData.age += 1; return jsonData; });
App Example: User Information Manager
Let’s create a simple app to manage user information using the LiveJSON APIs:
const liveJson = require('livejson'); // Initialize JSON with user data let users = liveJson.init([ { "name": "John", "age": 30, "city": "New York" }, { "name": "Jane", "age": 25, "city": "San Francisco" } ]); // Add a new user users.add({ "name": "Doe", "age": 22, "city": "Los Angeles" }); // Update user age users.get(0).set('age', 31); // Remove a user users.remove(1); // Get all user names let userNames = users.map(user => user.get('name')); console.log(userNames); // Output: ['John', 'Doe']
With LiveJSON, managing and manipulating JSON data is intuitive and efficient, paving the way for smoother application development.
Hash: a21276119009f0e30c1cf4704c53e9336cc4c174294bb2cec5410c37af29379b