JSON parsing and generation
Almost all mainstream programming languages now provide libraries to parse and generate JSON data.
JavaScript
JavaScript provides built JSON.parse()
and JSON.stringify()
two functions to manipulate JSON.
JSON.parse()
JSON.parse() is used to parse JSON text into JavaScript data type.
usage:
JSON.parse('{}'); // {}
JSON.parse('true'); // true
JSON.parse('"foo"'); // "foo"
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
JSON.parse('null'); // null
JSON.stringify()
JSON.stringify() is used to convert JavaScript data type into JSON text.
usage:
JSON.stringify({}); // '{}'
JSON.stringify(true); // 'true'
JSON.stringify('foo'); // '"foo"'
JSON.stringify([1, 'false', false]); // '[1,"false",false]'
JSON.stringify({ x: 5 }); // '{"x":5}'
Python
Python also provides a built-in json library to manipulate JSON.
json.loads()
json.loads() is used to parse JSON text into Python data type.
>>> import json
>>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
[u'foo', {u'bar': [u'baz', None, 1.0, 2]}]
json.dumps()
json.dumps() is used to convert Python data type into JSON text.
>>> import json
>>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
'["foo", {"bar": ["baz", null, 1.0, 2]}]'
PHP
PHP also has built json_decode()
and json_encode()
two functions operate JSON.
json_decode()
json_decode() is used to parse JSON text into PHP data type.
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
?>
The above will output:
object(stdClass)#1 (5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
array(5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
json_encode()
json_encode() is used to convert PHP data type into JSON text.
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
The above will output:
{"a":1,"b":2,"c":3,"d":4,"e":5}
Ruby
In Ruby you can use the json module to manipulate JSON.
JSON.parse()
JSON.parse() is used to parse JSON text into Ruby data type.
require 'json'
my_hash = JSON.parse('{"hello": "goodbye"}')
puts my_hash["hello"] => "goodbye"
The above will output:
{"goodbye"=>"goodbye"}
JSON.generate()
JSON.generate() is used to convert Ruby data type into JSON text.
require 'json'
my_hash = {:hello => "goodbye"}
puts JSON.generate(my_hash) => "{\"hello\":\"goodbye\"}"
The above will output:
{"{\"hello\":\"goodbye\"}"=>"{\"hello\":\"goodbye\"}"}
to_json
But JSON.generate() can only eat objects or arrays, and the to_json method can accept more Ruby classes.
require 'json'
puts JSON.generate(1)
A program error will occur above:
generate: only generation of JSON objects or arrays allowed (JSON::GeneratorError)
Use to_json instead:
require 'json'
puts 1.to_json
Correct output:
1
Post a Comment
0 Comments