JSONオブジェクトを作成し、普通に出力、整形して出力(pretty()
)します。
nim
var js = %*{
"name": "taro",
"age": 33,
"family": {
"wife": {
"name": "hanako",
"age": 34
},
"boy": {
"name": "ken",
"age": 5
},
"girl": {
"name": "moe",
"age": 1
},
}
}
echo "JSON object: ", js
# => JSON object: {"name":"taro","age":33,"family":{"wife":{"name":"hanako","age":34},"boy":{"name":"ken","age":5},"girl":{"name":"moe","age":1}}}
echo "Prettify: ", js.pretty()
# |
# v
#Prettify: {
# "name": "taro",
# "age": 33,
# "family": {
# "wife": {
# "name": "hanako",
# "age": 34
# },
# "boy": {
# "name": "ken",
# "age": 5
# },
# "girl": {
# "name": "moe",
# "age": 1
# }
# }
#}
ここでgirl
要素へアクセスするにはカッコでくくりまくらないといけないわけです。
nim
echo js["family"]["girl"] # =>{"name":"moe","age":1}
PythonならSimpleNamespace を使ってnamedtupleに変換できます。
python
import json
from types import SimpleNamespace
jstr='''{
"name": "taro",
"age": 33,
"family": {
"wife": {
"name": "hanako",
"age": 34
},
"boy": {
"name": "ken",
"age": 5
},
"girl": {
"name": "moe",
"age": 1
}
}
}'''
jobj=json.loads(jstr)
print(jobj["family"]["girl"])
# => {'name': 'moe', 'age': 1}
jprop=json.loads(jstr, object_hook=lambda x: SimpleNamespace(**x))
print(jprop.family.girl)
# => namespace(name='moe', age=1)
Nimで同じようにプロパティアクセスするには、型を指定して、toメソッドを使ってnamedtupleの代わりにオブジェクトへ変換するようです。
最初のNimコードに追記します。
nim
(...snip...)
type Person=object
name: string
age: int
type Family=object
wife: Person
boy: Person
girl: Person
type Household=object
name: string
age: int
family: Family
let jprop=js.to(Household)
echo jprop.family.girl
# => (name: "moe", age: 1)
Goのjson.Marshal()
ぽいと思いました。