Parse object to JSON

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Major_Sauce

Hello together,

I know in languages like Java you have GSON or in C# you have Newtonsoft-JSON which allows you to parse whole Objects into JSON and back.
Now, I created a little script called NetPacket.gd with this content:

var type
var data = []

I preloaded this in my root node and created an instance of it with the “.new()” method.
Then I filled the type and data from the root node. In the next step I´d like to convert the NetPacket to a json String and send it to my server. I can create a JSON String of the array inside the NetPacket by calling

JSON.print(packet.data)

but then I´d have to do this multiple times in order to get the the whole object parsed.
Is there a way to do it faster and in one step ?

Best regards,
Major

:bust_in_silhouette: Reply From: Eric Ellingson

There is a helper function to_json(packet.data) that should do what you want.

Hi Eric,

thank you for the fast reply.
I just tried

		print(to_json(login)) 

which by the way does not have to be used on an object, just if anyone is curious.
So basically you can use it anywhere in your gs-script by simply calling to_json(var)
The result I get is “[Node:1132]” which is exactly the same thing that I got when I called JSON.print(var)
Oh, just to make things clear, the NetPacket.gd extends Node

Any ideas ?

Best regards,
Major

Major_Sauce | 2019-03-16 19:09