Sign In Register

How can we help you today?

Start a new topic
Answered

Dynamic JSON

Hello,


I want to create a dynamic json object, but instead of using the variable value, it uses the name of the variable as the key. The value part works fine. Here is my cloud code.


 

var kingdomRessList = Spark.runtimeCollection("kingdomRess")

var kingdomName = Spark.getData().KINGDOMNAME;
var ressName = Spark.getData().RESSNAME;
var ressAmount = Spark.getData().RESSAMOUNT;

var kingdomRess = {ressName:ressAmount};

kingdomRessList.update
(
    {"kingdomName":kingdomName},
    {"$inc":kingdomRess},
    true,
    false
)

 I found a tutorial about dynamic json but my json object will not work properly.
Here is the code from the tutorial.

 

//Declare key and data from attributes passed in
var dataKey = Spark.getData().dataKey;
var dataVal = Spark.getData().dataVal;

//Retrieve game data collection
var gameDataCollection = Spark.runtimeCollection("gameData");

//Build data using keyValue pair and data
var dynamicJSON = {dataKey:dataVal};

//Update the collection using the $set function - we're using the _id field to find the document
gameDataCollection.update({_id: {"$oid": "570ba4f37f416a06026e5cc8"}}, {$set:dynamicJSON});

 Thank you for your help.


Best Answer

Hey Phillip,


What sort of errors are you seeing? I would recommend trying this:

 

//Initialize "dynamicJson" as an empty dictionary/JavaScript object
var dynamicJson = {};

//At the key "dataKey", store "dataValue"
dynamicJson[dataKey] = dataValue;

JavaScript gets fussy when you use the syntactic sugar for initializing a dict/object with variable name keys. The second line of code in my code does exactly the same thing as line 9 of your code.


Answer

Hey Phillip,


What sort of errors are you seeing? I would recommend trying this:

 

//Initialize "dynamicJson" as an empty dictionary/JavaScript object
var dynamicJson = {};

//At the key "dataKey", store "dataValue"
dynamicJson[dataKey] = dataValue;

JavaScript gets fussy when you use the syntactic sugar for initializing a dict/object with variable name keys. The second line of code in my code does exactly the same thing as line 9 of your code.


1 person likes this

Hey Ryan,


thank you, that solved the problem.

Login to post a comment