YoYoGames / GameMaker-Bugs

Public tracking for GameMaker bugs
21 stars 8 forks source link

Struct "toJson()"-function #2891

Open HannulaTero opened 11 months ago

HannulaTero commented 11 months ago

Is your feature request related to a problem?

When I am making JSON-string from structs, many times I don't need all things struct has to be included in json. To avoid this, I need manually create another structure, which is then explicitly made into json. For simple struct this can be easy, but when there are nested structs, the problem becomes harder.

Describe the solution you'd like


In short, toJson() makes target struct provide another structure to be stringified into json instead of itself.


I propose struct toJson() method, which is triggered when struct is being made into JSON-string by json_stringify(struct); This should work similar 'toString()', the idea being that instead of default action, it will return something else instead.


Let's take a example what I mean.

// Example constructor
function Foo() constructor {
  name = "foo";
  data = {
    array: array_create(8, 0)
    some: 1
  };
  some = 2;
  thing = 3;

  toString = function() {
    return name;
  }

  toJson = function() {
    return [name, data.array]; 
  }
}

// Example use
var foo = new Foo();
var json = json_stringified(foo);
show_debug_message(foo);     // Prints: "foo"
show_debug_message(json);    // Prints: "["foo", [0, 0, 0, 0, 0, 0, 0, 0]]"

In the example we have several different kind of variables, holding different things. Now in the example we try print foo-struct as it is. Without toString, it would stringify and print all information. Now with toString, we return some other string to represent foo. In this case content of name.

Normally json_stringify(...) will make all contents of the struct into JSON-string from it, and toString or toValue doesn't affect it. Now my proposed toJson would behave similar to toString or toValue. Instead of using struct itself, toJson will provides another structure, which is then used for actual json-stringifying instead.


Describe alternatives you've considered

No response

Additional context

No response

adam-coster commented 11 months ago

Given the parallel with JavaScript, and the web target, toJSON() is an alternative that JavaScript uses so that might be a good choice.

thennothinghappened commented 8 months ago

on this I'd love to see some kind of deserializer type thing for constructors that tries to do the opposite given JSON without writing heaps of boilerplate to do that safely

HannulaTero commented 8 months ago

on this I'd love to see some kind of deserializer type thing for constructors that tries to do the opposite given JSON without writing heaps of boilerplate to do that safely

The latest beta introduced optional JSON filters for both parsing and stringifying, and Alice already made Utility-functions, which basically does "toJson" behaviour and back. Forum post