I checked how to encode and decode JSON in Python, Ruby, JavaScript, PHP.
test_json.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#
import json
#Dictionary format data
dic1 = {"key1": None, "key2": None}
dic1["key1"] = 24
dic1["key2"] = 45
print dic1
#Convert from dictionary format to JSON
json_data1 = json.dumps(dic1, sort_keys=True,indent=4)
print json_data1
json_data2 = json.dumps(dic1,sort_keys=True)
print json_data2
json_data3 = json.dumps(dic1)
print json_data3
dic2 = json.loads(json_data1)
print dic2
#Reconvert from JSON to dictionary format
dic2 = json.loads(json_data2)
print dic2
dic2 = json.loads(json_data3)
print dic2
#Reconfirm element
print dic2["key1"]
print dic2["key2"]
Execution result
$ ./test_json.py
{'key2': 45, 'key1': 24}
{
"key1": 24,
"key2": 45
}
{"key1": 24, "key2": 45}
{"key2": 45, "key1": 24}
{u'key2': 45, u'key1': 24}
{u'key2': 45, u'key1': 24}
{u'key2': 45, u'key1': 24}
24
45
test_json.rb
#!/usr/bin/env ruby
# -*- coding:utf-8 -*-
#
require 'json'
#Hash format data
h = {"key1" => 10, "key2" => 40, "key3" => "Window10"}
p h
p h["key1"]
p h["key2"]
p h["Windows10"]
#Convert from hash to JSON format
j = JSON.generate(h)
p j
#Convert from JSON to hash
x = JSON.parse(j)
p x
Execution result
$ ./test_json.rb
{"temp"=>10, "humid"=>40, "pos"=>"window"}
10
40
"window"
"{\"temp\":10,\"humid\":40,\"pos\":\"window\"}"
{"temp"=>10, "humid"=>40, "pos"=>"window"}
A script that can be executed from the command line.
test_json.js
#!/usr/bin/env nodejs
//
var sys = require('util');
//Associative array
var d = { key1: 24 , key2: 45 , key3: "Windows10"};
sys.print(d['key1']+"\n")
sys.print(d['key2']+"\n")
sys.print(d['key3']+"\n")
//From associative array to JSON format
var json_text = JSON.stringify(d);
sys.print(json_text + "\n")
//Return from JSON format to an associative array object
var obj = JSON.parse(json_text)
sys.print(obj['key1']+"\n")
sys.print(obj['key2']+"\n")
sys.print(obj['key3']+"\n")
Execution result
$ ./test_json.js
24
45
Windows10
{"key1":24,"key2":45,"key3":"Windows10"}
24
45
Windows10
test_json.php
#!/usr/bin/env php5
<?PHP
/*Associative array*/
$arr = array('key1' => 24, 'key2' =>45, 'key3' => 'windows');
print "{$arr['key1']}\n";
print "{$arr['key2']}\n";
print "{$arr['key3']}\n";
/*Convert to JSON format text*/
$json_text = json_encode($arr);
print "{$json_text}\n";
/*Convert to an associative array*/
$obj = json_decode($json_text);
print "{$obj->{'key1'}}\n";
print "{$obj->{'key2'}}\n";
print "{$obj->{'key3'}}\n";
?>
Execution result
$ ./test_json.php
24
45
windows
{"key1":24,"key2":45,"key3":"windows"}
24
45
windows
Recommended Posts