考慮:
>>> s
'[{"measurement": "cpu_load_short","tags": {"host": "server999","region": "us-west-1"},"fields": {"value": 0.99}},{"measurement": "cpu_load_short","tags": {"host": "server888","region": "us-east-1"},"fields": {"value": 0.88}}]'
您可以使用json
>>> import json
>>> json.loads(s)
[{u'fields': {u'value': 0.99}, u'tags': {u'host': u'server999', u'region': u'us-west-1'}, u'measurement': u'cpu_load_short'}, {u'fields': {u'value': 0.88}, u'tags': {u'host': u'server888', u'region': u'us-east-1'}, u'measurement': u'cpu_load_short'}]
或者ast
:
>>> import ast
>>> ast.literal_eval(s)
[{'fields': {'value': 0.99}, 'tags': {'host': 'server999', 'region': 'us-west-1'}, 'measurement': 'cpu_load_short'}, {'fields': {'value': 0.88}, 'tags': {'host': 'server888', 'region': 'us-east-1'}, 'measurement': 'cpu_load_short'}]
他們產生相同的Python數據結構(至少用ascii輸入...):
>>> json.loads(s)==ast.literal_eval(s)
True
因爲在每種情況下結果是Python dict
知道順序可能不同於字符串的順序。 Python字典是無序的,通常與創建順序不同(至少在Python 3.6之前)。
下的Python 3.6,它們產生字典是在同一順序:
>>> json.loads(s)
[{'measurement': 'cpu_load_short', 'tags': {'host': 'server999', 'region': 'us-west-1'}, 'fields': {'value': 0.99}}, {'measurement': 'cpu_load_short', 'tags': {'host': 'server888', 'region': 'us-east-1'}, 'fields': {'value': 0.88}}]
>>> ast.literal_eval(s)
[{'measurement': 'cpu_load_short', 'tags': {'host': 'server999', 'region': 'us-west-1'}, 'fields': {'value': 0.99}}, {'measurement': 'cpu_load_short', 'tags': {'host': 'server888', 'region': 'us-east-1'}, 'fields': {'value': 0.88}}]
的Python 3.6是偉大的......
沒有被切斷。這是一本字典,因此順序是任意的。 –
AWS API返回JSON數據 –