Json
Working with JSON Functions Example
Importing Functions:
First, we import the necessary JSON-related functions from the
mvk-project
package:newCommand
: Used to define a new command.jsonParse
: Parses a JSON string into a JavaScript object.jsonPretty
: Formats the JSON object into a pretty-printed string.json
: Retrieves the value of a specific key from the JSON object.jsonExists
: Checks if a specific key exists in the JSON object.jsonSet
: Sets a new key-value pair in the JSON object.jsonStringify
: Converts the JSON object back into a string.jsonUnset
: Removes a key-value pair from the JSON object.jsonClear
: Clears all key-value pairs in the JSON object.
Defining a New Command:
We define a new command named
test-command
. This command will be executed when invoked, and it will manipulate a JSON object in various ways.Parsing and Manipulating JSON:
We start by defining a JSON string
iJson
. ThejsonParse
function is then used to parse this string into a JavaScript object, allowing us to manipulate it.Using JSON Functions:
jsonPretty(4)
: Formats the JSON object into a pretty-printed string with an indentation of 4 spaces.json({ key: 'name' })
: Retrieves the value associated with the keyname
.jsonExists({ key: 'years' })
andjsonExists({ key: 'address' })
: Checks if the keysyears
andaddress
exist in the JSON object, returningtrue
orfalse
.jsonSet({ key: 'address', value: 'Street 1085' })
: Sets a new key-value pairaddress: 'Street 1085'
in the JSON object.jsonStringify()
: Converts the modified JSON object back into a string format.jsonUnset({ key: 'adult' })
: Removes the keyadult
from the JSON object.jsonClear()
: Clears all key-value pairs from the JSON object.
Final Code:
Function Descriptions:
This example demonstrates how to parse a JSON string, manipulate its content using various functions, and then convert it back into a string. Each function allows for different types of interactions with the JSON object, making it a powerful tool for handling JSON data in your bot commands.
Last updated