我被要求生成,并且稍后再读回一个看起来像这样的json对象:
$ python -c 'import chainer; chainer.print_runtime_info()'
Platform: Linux-4.4.0-103-generic-x86_64-with-debian-stretch-sid
Chainer: 5.3.0
NumPy: 1.16.2
CuPy:
CuPy Version : 5.3.0
CUDA Root : /usr/local/cuda
CUDA Build Version : 9020
CUDA Driver Version : 9020
CUDA Runtime Version : 9020
cuDNN Build Version : 7402
cuDNN Version : 7500
NCCL Build Version : 2307
NCCL Runtime Version : 2402
iDeep: Not Available
通常,我会使用python dict并将其转换为json。但是,这里的问题是list和sub-dict都是匿名的。
我认为不可能做出这样的命令,对吗?
答案 0 :(得分:1)
这不是有效的json对象,但是您可以为列表部分添加一个键。喜欢:
{"name":"somename","value" : [{"id":123,"key1":"anydata"},{"id":345,"key1":"x","key3":"yz"}]}
现在这是一个有效的json字符串。
>>> a = ast.literal_eval('{"name":"somename","value" : [{"id":123,"key1":"anydata"},{"id":345,"key1":"x","key3":"yz"}]}')
>>> print(a['name'])
>>> 'somename'
>>> print(a['value'][0]['id'])
>>> 123
对于变量列表,它很简单:
anon_list = [{"id":123,"key1":"anydata"},{"id":345,"key1":"x","key3":"yz"}]
a = {"name":"somename","value" : anon_list}
>>> print(a['name'])
>>> 'somename'
>>> print(a['value'][0]['id'])
>>> 123