Jump to content

Sending structured data between objects using JSON


Extrude Ragu
 Share

You are about to reply to a thread that has been inactive for 1453 days.

Please take a moment to consider if this thread is worth bumping.

Recommended Posts

Some people struggle with sending structured data between one object and another and resort to using multiple messages which is a bit slower.

Below is a simple example that demonstrates how to send structured data from one object to another as a json encoded string, and then decode the json back in the receiver.

In this case, I am sending my name, my age, and a list of my hobbies in one string.

Sender Object's Script

string avatarName = "Ai";
integer avatarAge = 11;
list avatarHobbies = ["Mesh modelling","Scripting"];

default
{
    touch_start(integer num_detected)
    {
        list json_values = [
            "avatarName", avatarName,
            "avatarAge", avatarAge,
            "avatarHobbies", llList2Json(JSON_ARRAY, avatarHobbies)
        ];
        string json = llList2Json(JSON_OBJECT, json_values);
        llSay(10, json);
    }
}

Receiver Object's Script

default
{
    state_entry()
    {
        llListen(10, "", NULL_KEY, "");
    }

    listen(integer channel, string name, key id, string message)
    {
        string avatarName = llJsonGetValue(message, ["avatarName"]);
        integer avatarAge = (integer) llJsonGetValue(message, ["avatarAge"]);
        list avatarHobbies = llJson2List(llJsonGetValue(message, ["avatarHobbies"]));

        llOwnerSay(
            "Avatar Name: " + avatarName 
            + "\nAvatar Age: " + (string)avatarAge
            + "\nAvatar Hobbies: " + llList2CSV(avatarHobbies));
    }
}

As you can see, the script remains fairly readable.

I leave the nitty gritty of why this works as an exercise to the reader, however I think the above examples should be enough for most readers to get to where they want to be without being overwhelmed.

Pro's and Cons

The main benefit of sending data as Json between objects is that it is possible to send complex structured data in a single message. It makes it easy to add values without breaking existing systems too.

A significant drawback is that parsing Json is slower as the message must be decoded by the server.

Alternatives

If you are looking to just send a flat unstructured list of data between one object and another, the best option is to use llList2CSV to convert a list to a CSV encoded string, and llCSV2List to convert it back in the receiver.

Link to comment
Share on other sites

You are about to reply to a thread that has been inactive for 1453 days.

Please take a moment to consider if this thread is worth bumping.

Please sign in to comment

You will be able to leave a comment after signing in



Sign In Now
 Share

×
×
  • Create New...