Jump to content


Photo

How to work with JSON data?


  • Please log in to reply
4 replies to this topic

#1 markus_ja

markus_ja
  • Members
  • 319 posts
  • LocationAustria

Posted 24 May 2016 - 06:32 PM

Hello,

 

my rest server is returning a JSON string. How can I parse it as JSON Object, in order I can access the values properly?

 

Here is my code snippet:

REST[W3EditBox1.Text,''].Call
    .OnDone(
      procedure(http: TW3HttpRequest)
      begin
        W3Memo1.Text := http.ResponseText;
      end)
    .onError(
      procedure(http: TW3HttpRequest)
      begin
        W3Memo1.Text := http.ResponseText;
      end)
    .Get;


#2 Christian-W. Budde

Christian-W. Budde
  • Members
  • 334 posts
  • LocationGermany

Posted 24 May 2016 - 07:04 PM

The JSON data can directly be used as an object. If, for instance, your data looks like this:

{
  "Foo": "Bar"
}

you can write something like:

uses
  ECMA.JSON, W3C.Console;

[...]
var Data := JSON.Parse(http.ResponseText);

Console.Log(Data.Foo);

which would write 'Bar' to the console.

 

If you want to use type information, you can write something like this:

uses
  ECMA.JSON, W3C.Console;

type
  JFooBar = class external
    Foo: String;
  end;

[...]
var Data := JFooBar(JSON.Parse(http.ResponseText));

Console.Log(Data.Foo);

The advantage of this approach is the fact that now code completion is aware of the 'Foo' member.

 

However, keep in mind that the type cast is unsafe. If the JSON data is not the class JFooBar it will result in an unpredictable behaviour (depending on read or write access).


  • Nico Wouterse likes this

#3 markus_ja

markus_ja
  • Members
  • 319 posts
  • LocationAustria

Posted 25 May 2016 - 09:04 AM

Thanks!



#4 Dany

Dany
  • Members
  • 127 posts

Posted 25 May 2016 - 03:15 PM

Brilliant answer, Christian!

 

I'm sure it's possible to find, and i know it's been discussed, but i like to point out that the "class external" approach goes both ways too. Sometimes (because of the way some name need to change from pascal to js even regardless of code obfuscation) the "class external" approach is much better than to JSON.stringify records.



#5 Dany

Dany
  • Members
  • 127 posts

Posted 24 June 2016 - 09:55 AM

Is it possible to define a class for this JSON and cast to it as above? Would anyone care to write an example?

{id: 1, values: [{"name":"one", value:55, used:true}, {"name":"two", value:65, used:false}]}

Also how would a object definition look? I.e. something like:

var object := class id: Integer = 1; values ..?... end;

TIA,

 

/D






0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users