Learn JSON KV
In this template, you will learn how to save JSON objects in KV.
Install
To install this app, press the big green button above.
How to use?
Generating components
In the set.js
file, we are going to save the JSON object in KV. But before wo do this we have to define the values we want to save in the object:
let id = '';
for (let i = 0; i < 16; i++) {
id += Math.floor(Math.random() * 10);
}
const timestamp = Date.now();
const error = "I am a test error!"
In the first line we generate an id
. This id is a unique ID.
After we generated the id we are getting the current timestamp.
Last but not least, we define a sample error.
Tip!
These are examples of what you can save in your JSON object! You can save whatever you want.
Defining JSON object
Now that we have our components, we can define our object:
const requestdata = {
id: `${id}`,
timestamp: `${timestamp}`,
error: `${error}`,
};
Storing in KV
We have our JSON object defined so now we can store it in KV:
await lib.utils.kv['@0.1.16'].set({
key: `data_${id}`,
value: requestdata
});
We use the generated id as a key to retrieve the value later. You can choose any unique value to use as a key, such as a string or a number. Ex: Discord User Id
Retrieving KV value
Now that the JSON object is saved, we can retrieve it using our key in get.js
.
data_${id}
const jsonObject = await lib.utils.kv['@0.1.16'].get({
key: `data_${id}`
});
The value is now saved in jsonObject
To make sure we can see what the JSON object is, we log it:
console.log('Entire JSON object:', jsonObject);
Now we have logged the entire object. But what if we only want a specific component?
console.log('ID:', jsonObject.id);
console.log('Timestamp:', jsonObject.timestamp);
console.log('Error:', jsonObject.error);
FAQ
Why would I use a JSON object instead of multiple KVs?
Using a JSON object instead of multiple KVs can make your code simpler and faster. It can help keep related data together, which makes it easier to update and retrieve information. This can save you time and prevent errors in your code.
Can I use this in a Discord bot?
Yes you can! You can use KV and JSON object for any API. To make it easier to use, you can replace the id with the user ID
Can I change the JSON components?
Yes you can! You can change the components in whatever you want.
What does this mean: TypeError: Cannot read property 'id' of null (in "get.js")
This means that the JSON object was empty:
- The JSON you saved was invalid
- Your id was invalid
Support
Credits
No credits! If you think this is a mistake, DM me on Discord!