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
}
]
}
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)
Both YAML / TOML have advantages and disadvantages, but those who are accustomed to JSON felt that TOML was easier to read.
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