我正在将以下json写入如下文件:
with open('/etc/data_file.json', 'w') as f:
json.dump({"account":{"id":10,"user_id":10}}, f)
我知道写入是成功的,因为我可以阅读并打印文件:
with open('/etc/data_file.json') as json_file:
json_data = json.load(json_file)
print json_data
>>> {"account":{"id":10,"user_id":10}}
但是如果我尝试访问其中一个密钥,那么我会收到以下错误消息:
print json_data["account"]
>>> TypeError: string indices must be integers
我不明白。我想要hash / dict行为,这就是我对数组/列表的期望。我对蟒蛇很新,来自红宝石,所以这对我来说真的很奇怪。
答案 0 :(得分:0)
Python 2.7.6 (default, Nov 10 2013, 19:24:18) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>>
>>>
>>> import json
>>> with open( 'data_file.json', 'w' ) as f:
... json.dump( { "account": { "id": 10, "user_id": 10 } }, f )
...
>>> with open( 'data_file.json' ) as json_file:
... json_data = json.load( json_file )
...
>>> print json_data
{u'account': {u'user_id': 10, u'id': 10}}
>>>
>>> print json_data[u'account']
{u'user_id': 10, u'id': 10}
>>> print json_data["account"]
{u'user_id': 10, u'id': 10}
>>>