How to handle JSON in Ruby, Python, JavaScript, PHP

I checked how to encode and decode JSON in Python, Ruby, JavaScript, PHP.

For Python

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

For Ruby

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"}

For JavaScript

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

For PHP5

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

How to handle JSON in Ruby, Python, JavaScript, PHP
How to handle Japanese in Python
How to write Ruby to_s in Python
How to create a JSON file in Python
[Introduction to Python] How to handle JSON format data
How to handle datetime type in python sqlite3
How to develop in Python
Handle prime numbers in Python / Ruby / PHP / Golang (Go)
python, php, ruby How to convert decimal numbers to n-ary numbers
[Python] How to do PCA in Python
How to handle session in SQLAlchemy
How to collect images in Python
How to use SQLite in Python
[Introduction to Python] How to parse JSON
How to wrap C in Python
How to use ChemSpider in Python
How to use PubChem in Python
[Introduction to Python] How to use class in Python?
How to not escape Japanese when dealing with json in python
How to access environment variables in Python
How to do R chartr () in Python
[Itertools.permutations] How to put permutations in Python
How to work with BigQuery in Python
How to get a stacktrace in python
Difference in how to write if statement between ruby ​​and python
How to display multiplication table in python
How to extract polygon area in Python
How to check opencv version in python
How to handle consecutive values in MySQL
How to switch python versions in cloud9
How to adjust image contrast in Python
How to use __slots__ in Python class
How to dynamically zero pad in Python
How to use regular expressions in Python
How to display Hello world in python
How to use is and == in Python
Let's see how to count the number of elements in an array in some languages [Go, JavaScript, PHP, Python, Ruby, Swift]
How to write the correct shebang in Perl, Python and Ruby scripts
How to use the C library in Python
How to enjoy programming with Minecraft (Ruby, Python)
[REAPER] How to play with Reascript in Python
How to clear tuples in a list (Python)
How to generate permutations in Python and C ++
To execute a Python enumerate function in JavaScript
How to embed a variable in a python string
How to implement Discord Slash Command in Python
Summary of how to import files in Python 3
How to simplify restricted polynomial fit in python
How to use Python Image Library in python3 series
How to implement shared memory in Python (mmap.mmap)
How to generate a Python object from JSON
How to specify TLS version in python requests
How to handle Linux commands well from Python
Use cryptography module to handle OpenSSL in Python
How to notify a Discord channel in Python
How to get the files in the [Python] folder
How to use tkinter with python in pyenv
How to run Leap Motion in non-Apple Python
POST JSON in Python and receive it in PHP
[Python] How to draw a histogram in Matplotlib
How to output "Ketsumaimo" as standard output in Python