Está en la página 1de 3

http://lazplanet.blogspot.com/2014/09/a-simple-json-parsing-example.

html

A Simple JSON Parsing Example


(9.03.2014)

JSON is a very common data format now a days, especially in various APIs.
JSON or JavaScript Object Notation is a comma seperated data writing format.
It is easy for the humans to read & write. It is easy for the machines to read &
write. So it is a d@mn good format to put data in. See this example and you'll
get the idea:

{
"name1": value1,
"name2": value2
}

As you can see, the value is written in quotes followed by a colon (:) sign,
followed by a value is the basic structure. It is an example straight from the
wiki. Here's another one from the wiki:

{"user":
{ "userid": 1900,
"username": "jsmith",
"password": "secret",
"groups": [ "admins", "users", "maintainers"]
}
}

Seems complex at first. But as you can see, it is very straight forward. It is
fairly simple, especially when compared to other text based data structures
such as XML. Oh boy! Newbies have a nightmare writing XML codes. Those
sharp-edged, pointy angle brackets are not something which is easy to their
eyes!

But JSON is very simple. It can be broke down into several points:

- When you want to write a group of data you use a curly brackets ( { } ).
- The whole data is considered as a group and so it is enclosed in 2 curly
brackets, always. (Even when there is only one name/value pair.)
- Then you write names of values and then values. You separate them with a
colon (:)
- If you write a string anywhere, use double quotes ( " " ). And if you write
numeric data, don't use it.

That's it! So simple.

How about a simple pascal example to go with it? Okey, let's get to it!
Code Example

Start Lazarus. Create a new Application Project (Project -> New Project ->
Application -> OK).

Switch to Code View (F12). Add fpjson and jsonparser to the uses. These are
units which has functions to work with JSON.

uses
..., fpjson, jsonparser;

procedure TForm1.FormCreate(Sender: TObject);

var
json: String; //We can also use TJSONStringType instead of string.
J: TJSONData;

begin

json:='{"user":'+
'{ "userid": 1900,'+
'"username": "jsmith",'+
'"password": "secret",'+
'"groups": [ "admins", "users", "maintainers"]'+
'}'+
'}';

J:=GetJSON(json);

// We show the username from the data


// FindPath returns TJSONData
// So we use .AsString to convert it to string. This is line 2.
Caption := J.FindPath('user.username').AsString;

end;
Extending the example
(no)

Download Sample Code ZIP

http://wiki.freepascal.org/JSON
http://www.freepascal.org/docs-html/fcl/fpjson/index.html
http://svn.freepascal.org/cgi-bin/viewvc.cgi/trunk/packages/fcl-json/examples/

También podría gustarte