Variable Argument to JSON in JavaScript

How do I…

Convert a variable to JSON in JavaScript code. (extension to be precise)


I have an extension parameter called Data which is a structure variable.

image


In the code, the expected and working is structure variable (an object variable outside of GDevelop).

image

So I used an argument for a structure variable parameter… something like this:

image


Simply nothing happens on the server, and this message appears in the debugger:

image

I know that the “ToJSON” expression can be used in standard events but I haven’t found a function with the same name for JavaScript. (I checked the documentation, wiki and forums)


I know this error may seem silly. But the more silly it is, the faster someone answers.

I’m not sure what you’re doing. You can access variables directly but it depends on your needs.

Have you looked here?
https://docs.gdevelop.io/GDJS%20Runtime%20Documentation/classes/gdjs.Variable.html

Edit: not sure if this helps

toJSObject
toJSObject(): any
Defined in GDJS/Runtime/variable.ts:187
Converts this variable into an equivalent JavaScript object.

Returns any
A JavaScript object equivalent to the variable.

From chatgpt

// JavaScript object
let jsObject = {
    name: "John",
    age: 30,
    city: "New York"
};

// Convert the JavaScript object to a JSON string
let jsonString = JSON.stringify(jsObject);

// Output the JSON string
console.log(jsonString);

1 Like