C3 AI Documentation Home

Jsn

The Jsn Type is designed for manipulation and conversion of JSON nodes and regular data types.

This Type plays a role in applications that frequently interact with JSON data, offering a suite of methods to handle JSON in a variety of formats and contexts. A key advantage of the Jsn Type is its ability to maintain stable JSON serialized representations across different programming languages, addressing the inherent differences in data handling between languages.

Array creation and manipulation

Using the Jsn Type, you can initialize an empty JSON array using Jsn.array(). This method ensures that the created array j is indeed empty, as verified by checking j.length === 0. To demonstrate its serialization capabilities, Jsn.stringify(j) is used to convert the empty array into a string format, resulting in '[]'.

JavaScript
// Initializes an empty JSON array.
let j = Jsn.array();
// This line checks if the newly created JSON array `j` has no elements. It's an assertion to ensure the array
// initialization process creates an empty array.
j.length === 0;
// Converts the empty JSON array into a string. The expected output is a string representation of an empty array
// (`'[]'`), demonstrating the `Jsn` Type's ability to serialize JSON arrays into string format.
Jsn.stringify(j) === '[]';

Binary data handling

The Jsn Type facilitates the handling of binary data. By using Jsn.binary(...), you can transform binary data is into a JSON-compatible format. For instance, Bin.fromBase64(...) decodes a Base64 string, and Jsn.stringify(b) serializes this binary data into a JSON string, ensuring accurate representation in JSON format.

JavaScript
// This function transforms binary data into a JSON-compatible format. `Bin.fromBase64(...)` suggests that
// the binary data is being decoded from a Base64 string.
let b = Jsn.binary(Bin.fromBase64("SG93IG5vdywgYnJvd24gY293Pw=="));
// Serializes the binary data into a JSON string, ensuring the binary data is correctly represented in JSON format.
Jsn.stringify(b) === '"SG93IG5vdywgYnJvd24gY293Pw=="';

Boolean value processing

The Jsn Type's ability to process different data types into JSON booleans is demonstrated through the Jsn.bool(...) method. This function converts various inputs into boolean values in JSON format. Further, the serialization of these boolean values into JSON strings using Jsn.stringify(...) emphasizes the Type's consistency in data handling.

JavaScript
// Converts different inputs to boolean values in JSON format. This demonstrates the `Jsn` Type's ability to handle and
// convert various data types to JSON booleans.
Jsn.bool(null) == false;
Jsn.bool(true) == true;
// Here, the method is used to serialize the boolean value into a JSON string. This highlights the Type's consistency in
// handling and representing JSON data.
Jsn.stringify(Jsn.bool(false)) == "false";

General JSON value creation

This section showcases the Jsn Type's versatility in handling different data types through Jsn.make(...). This method is adept at creating JSON representations of booleans, strings, numbers, objects, and arrays. The subsequent serialization of these data types into JSON strings using Jsn.stringify(Jsn.make(...)) underlines the comprehensive data serialization capabilities of the Jsn Type.

JavaScript
// This method creates JSON representations of various data types - booleans, strings, numbers,
// objects, and arrays. It illustrates the flexibility of the `Jsn` Type in dealing with different types of data.
// Each `Jsn.stringify(Jsn.make(...))` call converts the respective data type into its JSON string equivalent,
// showcasing the Type's comprehensive data serialization capabilities.
Jsn.stringify(Jsn.make(true)) === 'true';
Jsn.stringify(Jsn.make([ "one fish", "two fish" ])) === '["one fish","two fish"]';

Object creation and serialization

The Jsn.object(...) method is pivotal in constructing complex JSON structures, allowing the creation of JSON objects with specified key-value pairs. The correctness of the JSON format for these objects is confirmed through serialization, which is done using Jsn.stringify(j), ensuring the integrity of the object's structure and data.

JavaScript
let j = Jsn.object("a", 14.7, "b", "lumpy gravy");
Jsn.stringify(j) === '{"a":14.7,"b":"lumpy gravy"}';
  • Jsn.object(...): Creates a JSON object with the provided key-value pairs. This method reflects the Jsn Type's ability to construct complex JSON structures.
  • The serialization (Jsn.stringify(j)) checks the correct JSON format of the created object, confirming the object's structure and data integrity.

Number handling

Jsn effectively converts numeric values into JSON-compatible formats, a crucial aspect for accurate data representation. This is evident from Jsn.number(...), which maintains numeric precision and format. Serializing these numbers into JSON strings using Jsn.stringify(Jsn.number(...)) further tests the Type's proficiency in handling numeric data.

JavaScript
Jsn.number(5.25) == 5.25;
Jsn.stringify(Jsn.number(5.25)) === '5.25';
  • Jsn.number(...): Converts a numeric value into its JSON-compatible format. This is crucial for ensuring that numeric data is accurately represented in JSON.
  • Serializing the number (Jsn.stringify(Jsn.number(...))) tests the Type's ability to maintain the numeric precision and format in the JSON string output.

Parsing JSON Strings

Jsn's parsing functionality, as demonstrated by Jsn.parse(...), efficiently converts JSON strings back into JavaScript data types. This ability to parse and subsequently serialize JSON strings is a testament to the Jsn Type's robust data handling capabilities.

JavaScript
Jsn.parse("true") == true;
Jsn.stringify(Jsn.parse("}x", true)); // throws error
  • Jsn.parse(...): Demonstrates the parsing functionality of the Jsn Type, which converts JSON strings back into their respective JavaScript data types.
  • The use of Jsn.stringify(...) on a parse

Temperature conversion to JSON

The function convertTemperatureToJson showcases the practical use of the Jsn Type in real-world scenarios. It converts a temperature from Celsius to Fahrenheit, creating a JSON object to hold both values, and then serializes this object into a string format for easy handling.

This function converts a temperature reading from Celsius to Fahrenheit and stores both values in a JSON object.

JavaScript
function convertTemperatureToJson(celsius) {
    const fahrenheit = (celsius * 9/5) + 32; // Convert Celsius to Fahrenheit
    const temperatureObj = Jsn.object("celsius", celsius, "fahrenheit", fahrenheit); // Create a JSON object with both values
    return Jsn.stringify(temperatureObj); // Convert the JSON object to a string and return
}
  • Line 1: Defines a function convertTemperatureToJson that takes a temperature in Celsius.
  • Line 2: Converts the given Celsius temperature to Fahrenheit.
  • Line 3: Creates a JSON object using Jsn.object with two key-value pairs: one for Celsius and one for Fahrenheit.
  • Line 4: Serializes the JSON object into a string using Jsn.stringify and returns it.

The convertTemperatureToJson function takes a temperature value in Celsius and converts it into Fahrenheit, then creates a JSON object containing both temperature values. Here's an example of how to use it:

JavaScript
// Example: Converting 25 Celsius to Fahrenheit and creating a JSON representation
let temperatureInCelsius = 25;
let temperatureJson = convertTemperatureToJson(temperatureInCelsius);

console.log(temperatureJson);
// Output should be a JSON string: '{"celsius":25,"fahrenheit":77}'

In this example, the function converts 25 degrees Celsius into Fahrenheit and then returns a JSON string representing both temperatures.

Parsing and logging JSON arrays

parseAndLogJsonArray is another practical function illustrating the Jsn Type's utility. It parses a JSON string representing an array of log messages and prints each message. This function highlights the Type's ability to parse and interact with JSON arrays.

JavaScript
function parseAndLogJsonArray(jsonString) {
    const logArray = Jsn.parse(jsonString); // Parse the JSON string into an array
    if (Array.isArray(logArray)) { // Check if the parsed data is an array
        logArray.forEach(message => console.log(message)); // Print each log message
    }
}
  • Line 1: Defines a function parseAndLogJsonArray that takes a JSON string.
  • Line 2: Parses the JSON string into a JavaScript array using Jsn.parse.
  • Line 3: Checks if the parsed object is an array.
  • Line 4: Iterates over the array and logs each message to the console.

The parseAndLogJsonArray function is designed to parse a JSON string representing an array and log each element of the array to the console. Here's how it can be used:

JavaScript
// Example: Parsing and logging a JSON array of messages
let jsonArrayString = '["Message 1", "Message 2", "Message 3"]';
parseAndLogJsonArray(jsonArrayString);

This example demonstrates parsing a JSON string containing an array of messages and then logging each message to the console.

Adding validated user data to a JSON array

The function validateAndAddUser validates user data and adds it to a JSON array of users, demonstrating the Jsn Type's capability in handling and validating JSON data. It parses a JSON string of users, validates new user data, and updates the JSON string accordingly.

JavaScript
function validateAndAddUser(userData, usersJson) {
    if (userData.name && userData.email) { // Validate user data
        const usersArray = Jsn.parse(usersJson) || []; // Parse the JSON string into an array or initialize a new array
        usersArray.push(userData); // Add the new user to the array
        return Jsn.stringify(usersArray); // Convert the array back to a JSON string and return
    }
    return usersJson; // Return the original JSON string if validation fails
}

The validateAndAddUser function takes user data and a JSON string representing an array of users. It validates the user data and, if valid, adds it to the array. Here's an example:

JavaScript
// Example: Adding a new user to a JSON array of users
let newUser = { name: "John Doe", email: "johndoe@example.com" };
let existingUsersJson = '[{"name":"Jane Doe", "email":"janedoe@example.com"}]';
let updatedUsersJson = validateAndAddUser(newUser, existingUsersJson);
console.log(updatedUsersJson);
// Output should be: '[{"name":"Jane Doe", "email":"janedoe@example.com"},{"name":"John Doe", "email":"johndoe@example.com"}]'

In this example, newUser is validated and added to the existing JSON array of users, existingUsersJson. The function returns the updated JSON string, including the new user.

  • Line 1: Defines a function validateAndAddUser that takes user data and a JSON string of users.
  • Line 2: Checks if the user data includes both a name and an email.
  • Line 3: Parses the existing users JSON string into an array, or creates a new one if parsing fails.
  • Line 4: Adds the new user to the users array.
  • Line 5: Serializes the updated array back into a JSON string.
  • Line 6: Returns the original JSON string if the user data is not valid.

These functions demonstrate practical applications of the Jsn Type in various scenarios, highlighting its flexibility and utility in handling JSON data within JavaScript environments. Each function is designed to be integrated into larger applications where JSON data manipulation is required.

Was this page helpful?