Jump to content
markus_ja

How to work with JSON data?

Recommended Posts

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;

Share this post


Link to post
Share on other sites

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).

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×