ibireme / yyjson

The fastest JSON library in C
https://ibireme.github.io/yyjson/doc/doxygen/html/
MIT License
2.98k stars 262 forks source link

Is there a method to store the array of primitive types? #163

Closed Diego-Hernandez-Moodys closed 3 months ago

Diego-Hernandez-Moodys commented 4 months ago

I'd like some help in extracting the non-object arrays.

I have a json like this and would like to store the "metadata" field to a char**

{
    "_id": str,
    "_score": double,
    "_source": 
    {
        "embedding": [ doubles ],
        "metadata": [ strs ]
    }
}

I can malloc and then iterate through the array, but I don't know how many values there are ahead of time, do I?

// Get the root["_source"]["metadata"] object
yyjson_val *source = yyjson_obj_get(root, "_source");
yyjson_val *metadata_array = yyjson_obj_get(source, "metadata")
yyjson_val *metadata;
int j;
int max_metadata;
yyjson_arr_foreach(metadata_array, j, max_metadata, metadata)
{
        const char* value = yyjson_get_str(metadata);
        // ??
}
ibireme commented 3 months ago

You can use yyjson_arr_size(arr) to get the size of an array, yyjson_get_len(str) to get the length of a string.

Diego-Hernandez-Moodys commented 3 months ago

And then I would use strdup to transfer the memory, right?

    int num_hits = yyjson_arr_size(items_array);
    char** outs = calloc(num_hits + 1, sizeof(char*));

    yyjson_arr_foreach(items_array, ix, max, item) 
    {
        const char* out = yyjson_get_str(item);
        outs[i] = strdup(out); // Copy each string
    }
ibireme commented 3 months ago

Yes, this works if you want to manage the strings yourself.

Diego-Hernandez-Moodys commented 3 months ago

Thanks, you may close unless you have another suggestion.