User:LepreKhaun Resident/Delete Json Element

From Second Life Wiki
Jump to: navigation, search

[NOTE: Pages within my Name Space are a WIP and constantly changing. As my understanding of the problems I attempt to address and the grasp of the subject matter itself deepens, I regularly review what I have written and update the content as better algorithms occur to me.

However, for this process of refinement, improvement and tweaking to result in something that might (hopefully!) benefit the community at large, I ask that comments, suggested improvements, corrections of fact or your own personal style preferences be made ONLY on the Discussion Pages within my Name Space. Thank you!]

<lsl> // Function: string deleteJsonElement( string jsonSource, list pathtoElement ); // Version 1.5 9/7/2013 Fixed case for a single item pathtoElement // Version 1.0 by LepreKhaun, 6/21/2013. Free to copy, modify and use as one wishes with this comment included. // This function takes a JSON text string and returns a copy of it with a specified element removed from it. // jsonSource is the JSON text to remove an element from. // pathToElement is a List containing the transversal path to the element // (as defined as "specifiers" in http://wiki.secondlife.com/wiki/Json_usage_in_LSL ) // AND ending with the element to remove. // The element may be an array Value or the "Key" within an object // If the parent of the element is a JSON_ARRAY, the element to be removed must be an integer INDEX // If the parent of the element is a JSON_OBJECT, the element to be removed must be a string "KEY" // // NOTE: This code is not optimized nor does it contain any error checking!!! // Add whatever you feel is needed to ensure correct operation of your script.

string deleteJsonElement( string jsonSource, list pathtoElement ) {

integer placeinlist;

// Obtain the JSON object of the parent of the element string jsonParent = llJsonGetValue( jsonSource, llDeleteSubList( pathtoElement, -1, -1 ) );

// Convert it to a list list listParent = llJson2List( jsonParent );

// Do test if (llJsonValueType( jsonParent, [] ) == JSON_ARRAY) { placeinlist = llList2Integer( pathtoElement, -1 ); listParent = llDeleteSubList( listParent, placeinlist, placeinlist );

// convert to a JSON object jsonParent = llList2Json( JSON_ARRAY, listParent );

} else // We are dealing with a JSON_OBJECT { placeinlist = llListFindList( listParent, llList2List( pathtoElement, -1, -1 ) ); listParent = llDeleteSubList( listParent, placeinlist, placeinlist + 1 );

// convert to a JSON object jsonParent = llList2Json( JSON_OBJECT, listParent ); }


// Insert our results and return return llJsonSetValue( jsonSource, llList2List( pathtoElement, 0, -2 ), jsonParent ); } </lsl>


== More Json Tips, Tricks and Coding Examples ==