question

Kim Strasser avatar image
Kim Strasser asked

How can I find certain keys in Title Data?

I want to add each Title Data key/value pair to an array that contains "Achievement" in the key. But I get an error message in this line:

var myObject = JSON.parse(result.Data);
"Error": {
            "Error": "JavascriptException",
            "Message": "JavascriptException",
            "StackTrace": "SyntaxError: Unexpected token o in JSON at position 1\n    at JSON.parse (<anonymous>)\n    at handlers.CheckPlayerAchievements (E5E2C-main.js:102:29)\n    at Object.invokeFunction (Script:117:33)"
        }
handlers.CheckPlayerAchievements = function (args, context)
{
    var result = server.GetTitleData({Keys: null});
    var keyname = "Achievement";
    var achievementkey;
    var achievkeyslist = [];
    var achievvalueslist = [];
   
    if (result.Data != null)
    {
        var myObject = JSON.parse(result.Data);
        var jsonitemskeys = Object.keys(myObject);
        var jsonitemsvalues = Object.values(myObject);
        
        jsonitemskeys.forEach(function(entry) {
        log.info("Key: " + entry);
        log.info("Value: " + myObject[entry]);

 	});
    }
    
    return;
}

How can I find out if a Title Data key/value pair contains "Achievement" in the key?

CloudScriptTitle Data
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

·
Rick Chen avatar image
Rick Chen answered

The result of server.GetTitleData is already a json, and trying to parse the result.Data, which is a value, will produce the “SyntaxError” you mentioned.

What you could do to fix the error is to remove the JSON.parse in line 11 of your code snippet.

CloudScript is written in JavaScript language. You can search how to find out if a string contains a substring in JavaScript. For example, you could refer to this document:

https://www.w3schools.com/jsref/jsref_includes.asp

Here is a fixed version of your CloudScript:

handlers.CheckPlayerAchievements = function (args, context)
{
    var result = server.GetTitleData({Keys: null});
    var keyname = "Achievement";
    var achievementkey;
    var achievkeyslist = [];
    var achievvalueslist = [];
   
    if (result.Data != null)
    {
        var myObject = result.Data;
        var jsonitemskeys = Object.keys(myObject);
        var jsonitemsvalues = Object.values(myObject);
        
        jsonitemskeys.forEach(function(entry) {
            if(entry.includes("test")){
                log.info("Key: " + entry);
                log.info("Value: " + myObject[entry]);
            }
 
 	});
    }
    
    return;
}
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.