Skip to content
Back

use json for attribute

  • 1
  • Web
  • Databases
  • General
  • Tools
  • Self Hosted
AmirFt04
28 Apr, 2024, 06:44

How can use json type for attribute in collections?

TL;DR
Developers can utilize a splitJsonString function in TypeScript to store lengthy JSON strings as arrays of strings in an Appwrite database. While Appwrite does not natively support querying on JSON due to its SQL structure, developers can store JSON as a string with a maximum length. Thereby, enabling efficient querying by avoiding the need to parse all data.
gaurav_ch
28 Apr, 2024, 07:16

you want to store json? then you can choose string and add maximum length. that is how I store json.

AmirFt04
28 Apr, 2024, 07:24

But when i want to add query to that stringfied json i need to get all data and then parse, but i want to get data from db with conditions not all data

gaurav_ch
28 Apr, 2024, 07:34

as far as I know, you cannot query on json. appwrite uses SQL for storing collections. it is not pureplay noSQL db like mongo

AmirFt04
28 Apr, 2024, 07:36

So what i can do to implement this?

Sam K
28 Apr, 2024, 10:52

I am getting around this by creating an String attribute as an array with max length, before storing the data I use JSON.stringfy and convert the string to an array of strings with the max length. When I retrieve the data join the array of strings and parse it back to JSON. is a bit of a process 😅

Sam K
28 Apr, 2024, 10:58

if you're using js/ts here's the code for getting the array of strings to save it in appwrite db

TypeScript
export const splitJsonString = (
  jsonString: string,
  maxLength: number
): string[] => {
  if (jsonString.length <= maxLength) {
    return [jsonString];
  }

  const chunks: string[] = [];
  let currentChunk = "";

  for (const char of jsonString) {
    // Check if adding the current character exceeds the maxLength
    if (currentChunk.length + char.length <= maxLength) {
      currentChunk += char;
    } else {
      // If adding the current character exceeds the maxLength, start a new chunk
      chunks.push(currentChunk);
      currentChunk = char;
    }
  }

  // Push the last chunk if it is not empty
  if (currentChunk.length > 0) {
    chunks.push(currentChunk);
  }

  return chunks;
};
Steven
28 Apr, 2024, 17:06

What exactly are you trying to store?

Reply

Reply to this thread by joining our Discord

Reply on Discord

Need support?

Join our Discord

Get community support by joining our Discord server.

Join Discord

Get premium support

Join Appwrite Pro and get email support from our team.

Learn more