0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

NimでJSONプロパティアクセスする

Last updated at Posted at 2022-06-25

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()ぽいと思いました。

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?