question

Kim Strasser avatar image
Kim Strasser asked

How can I read a user data json key/value pair in CloudScript?

I have this key/value pair in user data:

Key: Myjson
Value: {"Id":"1","Timestamp":"23.12.2020 10:30:00","Day":"Wednesday","Month":"December","Year":"2020"}

And I want to create an array with all the item keys of this json. But I don't know how to get the item keys from result:

var jsonitemskeys = [];
var result = server.GetUserData({PlayFabId: currentPlayerId, Keys: "Myjson"});
 
if ((result.Data.hasOwnProperty("Myjson")) && (result.Data.Myjson.Value != "") && (result.Data.Myjson.Value != null))
{
// Add the item keys to the array
        
}

I want to add the keys "Id", "Timestamp", "Day", "Month" and "Year" to the array jsonitemskeys = [] but I don't know how to do that in this case. How can I add the keys to the array?

CloudScript
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

1 Answer

·
Sarah Zhang avatar image
Sarah Zhang answered

As this thread said, you can use JSON.parse() method to covert the JSON string to the JSON object. Then you can use JS method Object.keys() to get the array of this object’s keys.

var jsonitemskeys = [];
var result = server.GetUserData({PlayFabId: currentPlayerId, Keys: ["Myjson"]});

if ((result.Data.hasOwnProperty("Myjson")) && (result.Data.Myjson.Value != "") && (result.Data.Myjson.Value != null))
{
    // Add the item keys to the array
    var myObject = JSON.parse(result.Data.Myjson.Value);
    jsonitemskeys = Object.keys(myObject);

}
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.