Sign In Register

How can we help you today?

Start a new topic
Answered

Get all Json Keys (or Values)

Hi GS Community, 
for my inventory system I want to be able to send multiple entries at once via json, for example:
e.g.
{

  "@class": ".LogEventRequest",

  "eventKey": "addToPlayerInventory",

  "items": {

      "x001" : 12,

      "x013" : 99,

      "x007" : 3

  }

}

and I have to check the inventory (Game Data) of the player if there is already an entry for "x001 or "x007" and so on, and then sum up the values... (if it does not exist create the entry with entered valu), everything works with just adding one item (not using JSON but a string and a number attribute in the event)
But I dont want to send x amount of events just to add multiple Items to the inventory. So I want to create a JSON locallly on the client and after finishing a round send that JSON file to GS.

With just a string and a number attribute (for sending just a single item per event) I could use e. g. ".PATH" and ".VAL" to get their corresponding entries, but with a JSON document I only get the whole document, and can only separate the content if I know the names of the keys.... 
"var key= Spark.data.items.x001"
But that does obviously not work in my case.

I didn't find anything about that in the API Documentation, and I only have a dirty solution in my mind to bypass that problem: use JSON.stringify, than split that into different parts and so on. But as already said, it seams dirty to, there must be a simpler way...



So how do I get all keys (and/or values but separate) from an JSON document?



thank you! :) 

Best Answer

Hi Patrick,


You can do this in cloud code using the javascript Object's 'keys' function. Using the example you provided above you could do the following:


var items = Spark.getData().items;

var keys = Object.keys(items); //returns an array of the keys present in 'items'

for(var k in keys){

    var keyName = keys[k];
    var value = items[keyName];

}


Try this out and let us know how it works for you.


Regards,

Vinnie


1 Comment

Answer

Hi Patrick,


You can do this in cloud code using the javascript Object's 'keys' function. Using the example you provided above you could do the following:


var items = Spark.getData().items;

var keys = Object.keys(items); //returns an array of the keys present in 'items'

for(var k in keys){

    var keyName = keys[k];
    var value = items[keyName];

}


Try this out and let us know how it works for you.


Regards,

Vinnie



2 people like this
Login to post a comment