Difference between revisions of "User:LepreKhaun Resident/Delete Json Element"

From Second Life Wiki
Jump to navigation Jump to search
(Created page with "<pre> // Function: string deleteJsonElement( string jsonSource, list pathtoElement ); // Version 1.0 by LepreKhaun, 6/21/2013. Free to copy, modify and use as one wishes with thi…")
 
m (Added footer.)
Line 49: Line 49:
}
}
</pre>
</pre>
----
<center>== [[User:LepreKhaun_Resident|'''More Json Tips, Tricks and Coding Examples''']] ==</center>

Revision as of 08:11, 1 September 2013

// Function: string deleteJsonElement( string jsonSource, list 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, llList2List( pathtoElement, 0, -2 ) );
	
	// 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 ); 
}

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