Mutual conversion between JSON and YAML / TOML in Python

Mutual conversion between JSON and YAML / TOML in Python

It is inconvenient that I can not write comments with JSON, so I tried YAML / TOML. Ini that uses configparser is out of scope this time.

If you are not familiar with the definition format, it is easier to understand how to convert the definition file you normally use to another format via a dictionary rather than writing the definition in YAML / TOML from the beginning. Since it is accessed via a dictionary inside the program, I don't think it is necessary to change the processing itself. This time, I would like to test based on the following data.

dat.json[test data]


{
  "country": "Japan",
  "user": [
    {
      "name": "Taro",
      "phone": ["111-222-3333", "222-333-4444"],
      "age": 10
    },
    {
      "name": "Hanako",
      "phone": ["555-666-777"],
      "age": 20
    }
  ]
}

Conversion method

In addition to json, use yaml and toml libraries.

JSON→YAML Use the yaml library to convert from JSON to YAML.

json2yaml.py


import yaml
import json

with open('dat.json') as file:
    #Dictionary from JSON
    obj = json.load(file)
    #YAML from the dictionary
    ym = yaml.dump(obj, Dumper=yaml.CDumper)
    print(ym)

Execution result


country: Japan
user:
- age: 10
  name: Taro
  phone:
  - 111-222-3333
  - 222-333-4444
- age: 20
  name: Hanako
  phone:
  - 555-666-777

YAML→JSON It seems better to use safe_load to load YAML files. The reference method is the same as JSON, so you can use it without any discomfort. (The processing result will be the same as before conversion, so it is omitted.)

yaml2json.py


with open('dat.yaml') as file:
    #Dictionary from YAML
    obj = yaml.safe_load(file)
    #JSON from dictionary
    js = json.dumps(obj, indent=2)
    print(js)

JSON→TOML Use the toml library to convert from JSON to TOML. Usage is the same as YAML and JSON. In addition, it seems that pytoml is not maintained.

json2toml.py


import toml
import json

with open('dat.json') as file:
    #Dictionary from JSON
    obj = json.load(file)
    #TOML from the dictionary
    tm = toml.dumps(obj)
    print(tm)

Execution result


country = "Japan"
[[user]]
name = "Taro"
phone = [ "111-222-3333", "222-333-4444",]
age = 10

[[user]]
name = "Hanako"
phone = [ "555-666-777",]
age = 20

I'm a little worried about the comma at the end of the phone item.

TOML→JSON Reading TOML is similar to JSON / YAML.

toml2json.py


with open('dat.toml') as file:
    #Dictionary from TOML
    obj = toml.load(file)
    #JSON from dictionary
    js = json.dumps(obj, indent=2)
    print(js)

Summary

Both YAML / TOML have advantages and disadvantages, but those who are accustomed to JSON felt that TOML was easier to read.

What I want to do in the future

I would like to implement TomlEncoder of toml.dumps independently to support the following. --Subsection indent support in TOML (equivalent to indent in json.dumps) --Removed the last comma in the array item

Recommended Posts

Mutual conversion between JSON and YAML / TOML in Python
Difference between == and is in python
Differences in authenticity between Python and JavaScript
difference between statements (statements) and expressions (expressions) in Python
Differences in syntax between Python and Java
Difference between @classmethod and @staticmethod in Python
Difference between append and + = in Python list
Difference between nonlocal and global in Python
Read and write JSON files in Python
Differences in multithreading between Python and Jython
[python] Difference between variables and self. Variables in class
[Python] Conversion memo between time data and numerical data
About the difference between "==" and "is" in python
Reading and writing CSV and JSON files in Python
Mutual conversion between fixed point and binary numbers
POST JSON in Python and receive it in PHP
Handling json in python
Difference between Ruby and Python in terms of variables
Mutual conversion between date and days elapsed from January 1, 2000
Pretty print json or yaml with color in python
Difference between return, return None, and no return description in Python
Compare "relationship between log and infinity" in Gauche (0.9.4) and Python (3.5.1)
Easily format JSON in Python
Conversion between unixtime and datetime
Stack and Queue in Python
Unittest and CI in Python
Python module num2words Difference in behavior between English and Russian
List concatenation method in python, difference between list.extend () and “+” operator
Difference between Ruby and Python split
Difference between java and python (memo)
MIDI packages in Python midi and pretty_midi
View photos in Python and html
Write JSON Schema in Python DSL
Sorting algorithm and implementation in Python
Manipulate files and folders in Python
About dtypes in Python and Cython
Dynamically load json type in python
Handling of JSON files in Python
Cooperation between python module and API
JSON encoding and decoding with python
Difference in how to write if statement between ruby ​​and python
Differences between Python, stftime and strptime
Check and move directories in Python
Difference between python2 series and python3 series dict.keys ()
Ciphertext in Python: IND-CCA2 and RSA-OAEP
Hashing data in R and Python
[Python3] Save the mean and covariance matrix in json with pandas
Function synthesis and application in Python
Export and output files in Python
Transcendental simple and clear! !! Difference between single quotes and double quotes in Python
Python logging and dump to json
[Python] Difference between function and method
Reverse Hiragana and Katakana in Python2.7
Reading and writing text in Python
[GUI in Python] PyQt5-Menu and Toolbar-
File open function in Python3 (difference between open and codecs.open and speed comparison)
Python --Difference between exec and eval
[Python] Difference between randrange () and randint ()
[Python] Difference between sorted and sorted (Colaboratory)
Create and read messagepacks in Python
[Python] Summary of conversion between character strings and numerical values (ascii code)