How to select a random JSON node?

Hello Everyone,

I’ve got a JSON string that contains multiple items like this:

{
“ColorsArray” : [{
“colorName” : “red”,
“colorWeight” : “dark”
},
{
“colorName” : “blue”,
“colorWeight” : “medium”
},
{
“colorName” : “brown”,
“colorWeight” : light"
}
]
}

Pretty straightforward. Now, from this list, I need to select two random colors and be able to get both the colorName and colorWeight (which I will place in another jsonItem which will be returned from my method). This is where I’m running into problems. I’m not sure how to select the random entries from the returned JSON. I’m sure it’s pretty simple and probable some sort of array function but I’m stuck Can anyone point me in the right direction?

Thanks!

Are you using the classic framework or the new framework to access the json? The answer will depend on this.

I’m using the classic framework as I’m using 2014r3.1.

When you read in this JSON, the top level will be an object (like a Dictionary) with one element, ColorsArray. Each element of the ColorsArray is an object with two elements, so you’d do it like this:

dim root as new JSONItem( jsonStringYouPosted )
dim arr as JSONItem = root.Value( "ColorsArray" )
dim arrUbound as integer = arr.Count - 1
for i as integer = 0 to arrUbound
  dim colorElement as JSONItem = arr( i )
  // Do something with colorElement
next i

Many thanks! That perfectly answers my question.

Jsonitem.Child will let you specify an index, so just use a random number (see Random.InRange) from 0 to JSONItem.Count-1.

dim colorsarray as JSONItem = js.child("ColorsArray") Dim r as new Random Dim c as integer = colorsarray.count-1 Dim randomColor as JSONItem = colorsarray.child(r.inrange(0,c))

To clarify, when the JSONItem holds an array, using json( index ) is an alias for json.Value(index ). If you’re sure the value you’ll be retrieving is another JSONItem, you can also use json.Child( index ). I prefer the former only because it’s less code and it makes it clear that the thing acts like an array, but use whichever suits your style.