2017-09-03 3 views
2

stackoverflow에서 여러 가지 유사한 질문을 검토했지만 데이터/문자열에 적용되는 답변을 찾을 수 없습니다.Python Dicts 목록의 문자열

나는 효과적으로 사전 목록 인 문자열을 가지고 있습니다. 필드에서 숫자는 큰 따옴표로 묶지 않습니다. 문자열을 평가하기 위해 ast를 사용하려고하면 문자열의 일부가 잘리지 않고 이유가 확실하지 않습니다. 누군가가이 문자열을 읽고 사전 목록을 작성하는 적절한 방법을 결정하도록 도와 줄 수 있습니까?

감사합니다,

>>> print(ascii_data) 
    [{"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}}] 
>>> x = ast.literal_eval(ascii_data) 
>>> print(x) 
    [{'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'}] 
+3

것도이 차단되지 않습니다. 순서가 임의적이므로 사전입니다. –

+0

AWS API가 JSON 데이터 –

답변

0

:

>>> 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'}] 

을 그리고 그들은 적어도 (같은 파이썬 데이터 구조를 생성 아스키 입력 포함 ...) :

>>> json.loads(s)==ast.literal_eval(s) 
True 

는 각각의 경우에 때문에 결과는 파이썬 dict이 순서는 문자열의 순서와 다를 수 있습니다 것을 알고있다. 파이썬 dict은 순서가 매겨지지 않고 일반적으로 생성 순서와 다릅니다 (최소한 파이썬 3.6 이전에는).


파이썬 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}}] 

파이썬 3.6이 중대하다 ...

+0

을 반환합니다. [Python 3.6 dicts] (https://docs.python.org/3/whatsnew/3.6.html#whatsnew36-compactdict)는 주문을 보존합니다. 하지만, 의존하지 않는 구현 세부 사항으로 간주되지만, 향후 변경 될 수 있습니다. –

+0

@ 존 B : 예제가 추가되었습니다. 감사 – dawg

0

사용 JSON.

In [1]: s = '''[{"measurement": "cpu_load_short","tags": {"host": "server999","region": "us-west-1"},"fields": {"value": 0.99}},{"measuremen 
    ...: t": "cpu_load_short","tags": {"host": "server888","region": "us-east-1"},"fields": {"value": 0.88}}]''' 

In [2]: import json 

In [3]: import pprint 

In [4]: pprint.pprint(json.loads(s)) 
[{'fields': {'value': 0.99}, 
    'measurement': 'cpu_load_short', 
    'tags': {'host': 'server999', 'region': 'us-west-1'}}, 
{'fields': {'value': 0.88}, 
    'measurement': 'cpu_load_short', 
    'tags': {'host': 'server888', 'region': 'us-east-1'}}] 
In [11]: json.loads(s)[0]['tags']['host'] 
Out[11]: 'server999' 
0

어때 대략 json.loads?

j = json.loads(ascii_data) 

ast.literal_eval는 최선의 선택되지 않을 수 있습니다. 데이터 소스가 일부 API에서 나온다면 분명 json 형식 일 것입니다.

dict 키의 순서가 중요한 경우 JSONDecoder에 object_pairs_hook 인수를 지정하십시오. (참조 : Can I get JSON to load into an OrderedDict in Python?)을 감안할 때