2010-09-08 18:15 UTC+0300 Mindaugas Kavaliauskas (dbtopas/at/dbtopas.lt)
+ harbour/src/rtl/hbjson.c
+ added JavaScript Object Notation (JSON) encoder, decoder functions
; C level functions:
char * hb_jsonEncode( PHB_ITEM pValue, HB_SIZE * pnLen );
pValue - value to encode;
pnLen - if pnLen is not NULL, length of returned buffer is
stored to *pnLen;
returns pointer to encoded JSON buffer. buffer must be fried
by the caller.
HB_SIZE hb_jsonDecode( const char * szSource, PHB_ITEM pValue );
szSource - JSON source;
pValue - item to store decoded value. Item value is
undetermined in case of error;
returns number of bytes decoded from the buffer. This allows
to use the remaining part of the buffer for some other
purposes. Returns 0 on error.
Harbour level functions:
hb_jsonDecode( cJSON, @xValue ) --> nLengthDecoded
hb_jsonEncode( xValue ) --> cJSON
Note:
- Harbour types unsupported by JSON (date, timestamp, etc.) are
encoded as null values;
- strings are encoded in UTF-8;
- JSON encode functions are safe for recursive arrays and hashes.
Recursive part of array or hash will be stored as null. JSON
encoder still allows to use same structure in the leaves, in
this case content will be duplicate.
I.e.:
xI := {1, NIL}
xI[2] := xI
? hb_jsonEncode( xI ) // [1,null]
but:
xI := {1, .T.}
xI := {2, xI, xI}
? hb_jsonEncode( xI ) // [2,[1,true],[1,true]]
Examplo de uso:
I just created this sample to test the new functions....
-----------------------> test.json (from json wikipedia page)
{
"firstName": "John",
"lastName": "Smith",
"age": 25,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021"
},
"phoneNumber": [
{
"type": "home",
"number": "212 555-1234"
},
{
"type": "fax",
"number": "646 555-4567"
}
]
}
------------------------> js.prg
procedure main
Local nLen
Local res
Local o
text = memoread( "test.json" )
nLen := hb_jsondecode( text, @res )
? nLen, " bytes decoded"
? "name:", res["firstName"]
? "postalcode:", res["address"]["postalCode"]
? "fax: "
o := 0
FOR EACH o IN res["phoneNumber"]
if o["type"] == "fax"
?? o["number"]
endif
NEXT
--------------> console output
444 bytes decoded
name: John
postalcode: 10021
fax: 646 555-4567
Se precisar ja sei que tem algo no harbour :-)
Saudações,
Itamar M. Lins Jr.