简体   繁体   English

使用ast.literal_eval时格式错误的字符串

[英]Malformed string while using ast.literal_eval

I used json dump and then json load on the same data. 我使用json dump然后json加载相同的数据。 The data is unicode so I converted it to string. 数据是unicode所以我将其转换为字符串。 Using the ast.literla_eval I tried to get the type of the string to dict but I am getting error Malformed String. 使用ast.literla_eval我试图得到字符串的类型dict但我得到错误格式错误的字符串。

output of json load is below json负载的输出低于

('data', u'{\n  "a": "spawning", \n  "addresses": "", \n  "image": "b", \n  "OS-EXT-STS:vm_state": "building", \n  "c:launched_at": null, \n  "d": "e (fgh)", \n  "user_id": "hhh", \n 
    "accessIPv4": "", \n  "accessIPv6": "", \n  "name": "kk", \n  "created": "2017-12-08T07:52:44Z", \n  "z:xyz": []\n}', <type 'unicode'>)

What I tried? 我尝试了什么?

        with open('openstack_list.json', 'w') as e:
            json.dump(check_output(['openstack', 'server', 'show', i, '-f', 'json']), e)
        with open('openstack_list.json', 'r') as a:
            data = json.load(a)
            new_data = data.encode('utf-8')  # output type is unicode
            dict_data = ast.literal_eval(new_data) # output type is string

I want output to be dictionary but I didnt get it. 我希望输出是字典,但我没有得到它。 Also, json load gives a unicode data so I believe new_data = data.encode('utf-8') is redundant. 此外,json load提供了unicode数据,所以我相信new_data = data.encode('utf-8')是多余的。 But if I use ast.literal_eval without encoding I get Malformed string error. 但是如果我ast.literal_eval没有编码的情况下使用ast.literal_eval ,我会收到格式错误的字符串错误。 In any case, I am not able to get the data type to be dictionary. 无论如何,我无法将数据类型变为字典。

Edits: 编辑:

Error: 错误:

Traceback (most recent call last):
  File "openstack_resource_list.py", line 84, in <module>
    output = get_resources()
  File "openstack_resource_list.py", line 47, in get_resources
    dict_data = ast.literal_eval(new_data)
  File "/usr/lib64/python2.7/ast.py", line 80, in literal_eval
    return _convert(node_or_string)
  File "/usr/lib64/python2.7/ast.py", line 63, in _convert
    in zip(node.keys, node.values))
  File "/usr/lib64/python2.7/ast.py", line 62, in <genexpr>
    return dict((_convert(k), _convert(v)) for k, v
  File "/usr/lib64/python2.7/ast.py", line 79, in _convert
    raise ValueError('malformed string')
ValueError: malformed string

The data before json dump : json转储前的数据:

"{\n  \"aaa\": null, \n  \"addresses\": \"inner-net=192.168.0.173, x.x.x.x\", \n  \"image\": \"aaa (aaa)\", 
    \n  \"aaa:vm_state\": \"active\", \n  \"aaa:launched_at\": \"2017-12-08T08:21:45.000000\", \n  \"flavor\": \"aaa4 (aaa)\", 
    \n  \"id\": \"aaa\", \n  \"security_groups\": [\n    {\n      \"name\": \"default\"\n    }\n  ], \n  \"user_id\": \"aaa\", 
    \n  \"OS-DCF:diskConfig\": \"MANUAL\", \n  \"accessIPv4\": \"\", \n  \"accessIPv6\": \"\", \n  \"progress\": 0, \n  \"Oaa:power_state\": 1, \n  \"project_id\": \"aaa\", 
    \n  \"config_drive\": \"\", \n  \"status\": \"ACTIVE\", \n  \"updated\": \"2017-12-08T08:21:45Z\", \n  \"hostId\": \"aaa\", \n  \"OS-SRV-USG:terminated_at\": null, 
    \n  \"key_name\": \"pg_ci\", \n  \"properties\": \"\", \n  \"OS-EXT-AZ:availability_zone\": \"nova\", \n  \"name\": \"taaa\", \n  \"created\": \"2017-12-08T08:21:31Z\", \n 
    \"os-extended-volumes:volumes_attached\": [\n    {\n      \"id\": \"aaa\"\n    }\n  ]\n}"

That data returned by check_output is already JSON, so you should not JSON-ify it again with json.dump . 通过返回的数据check_output已经是JSON,所以你应该再以JSON-IFY它json.dump You can just write it to the file as is, and the file will be a valid JSON file. 您可以按原样将其写入文件,该文件将是有效的JSON文件。 And you can load it into a Python object with json.loads : 您可以使用json.loads其加载到Python对象中:

import json
from pprint import pprint

s = """{\n  \"aaa\": null, \n  \"addresses\": \"inner-net=192.168.0.173, x.x.x.x\", \n  \"image\": \"aaa (aaa)\", 
    \n  \"aaa:vm_state\": \"active\", \n  \"aaa:launched_at\": \"2017-12-08T08:21:45.000000\", \n  \"flavor\": \"aaa4 (aaa)\", 
    \n  \"id\": \"aaa\", \n  \"security_groups\": [\n    {\n      \"name\": \"default\"\n    }\n  ], \n  \"user_id\": \"aaa\", 
    \n  \"OS-DCF:diskConfig\": \"MANUAL\", \n  \"accessIPv4\": \"\", \n  \"accessIPv6\": \"\", \n  \"progress\": 0, \n  \"Oaa:power_state\": 1, \n  \"project_id\": \"aaa\", 
    \n  \"config_drive\": \"\", \n  \"status\": \"ACTIVE\", \n  \"updated\": \"2017-12-08T08:21:45Z\", \n  \"hostId\": \"aaa\", \n  \"OS-SRV-USG:terminated_at\": null, 
    \n  \"key_name\": \"pg_ci\", \n  \"properties\": \"\", \n  \"OS-EXT-AZ:availability_zone\": \"nova\", \n  \"name\": \"taaa\", \n  \"created\": \"2017-12-08T08:21:31Z\", \n 
    \"os-extended-volumes:volumes_attached\": [\n    {\n      \"id\": \"aaa\"\n    }\n  ]\n}"""

d = json.loads(s)
pprint(d)

output 产量

{'OS-DCF:diskConfig': 'MANUAL',
 'OS-EXT-AZ:availability_zone': 'nova',
 'OS-SRV-USG:terminated_at': None,
 'Oaa:power_state': 1,
 'aaa': None,
 'aaa:launched_at': '2017-12-08T08:21:45.000000',
 'aaa:vm_state': 'active',
 'accessIPv4': '',
 'accessIPv6': '',
 'addresses': 'inner-net=192.168.0.173, x.x.x.x',
 'config_drive': '',
 'created': '2017-12-08T08:21:31Z',
 'flavor': 'aaa4 (aaa)',
 'hostId': 'aaa',
 'id': 'aaa',
 'image': 'aaa (aaa)',
 'key_name': 'pg_ci',
 'name': 'taaa',
 'os-extended-volumes:volumes_attached': [{'id': 'aaa'}],
 'progress': 0,
 'project_id': 'aaa',
 'properties': '',
 'security_groups': [{'name': 'default'}],
 'status': 'ACTIVE',
 'updated': '2017-12-08T08:21:45Z',
 'user_id': 'aaa'}

And if you want to make it into clean JSON, pass that Python object to json.dump or json.dumps 如果你想把它变成干净的JSON,把那个Python对象传递给json.dump或者json.dumps

print(json.dumps(d, indent=4))

output 产量

{
    "aaa": null,
    "addresses": "inner-net=192.168.0.173, x.x.x.x",
    "image": "aaa (aaa)",
    "aaa:vm_state": "active",
    "aaa:launched_at": "2017-12-08T08:21:45.000000",
    "flavor": "aaa4 (aaa)",
    "id": "aaa",
    "security_groups": [
        {
            "name": "default"
        }
    ],
    "user_id": "aaa",
    "OS-DCF:diskConfig": "MANUAL",
    "accessIPv4": "",
    "accessIPv6": "",
    "progress": 0,
    "Oaa:power_state": 1,
    "project_id": "aaa",
    "config_drive": "",
    "status": "ACTIVE",
    "updated": "2017-12-08T08:21:45Z",
    "hostId": "aaa",
    "OS-SRV-USG:terminated_at": null,
    "key_name": "pg_ci",
    "properties": "",
    "OS-EXT-AZ:availability_zone": "nova",
    "name": "taaa",
    "created": "2017-12-08T08:21:31Z",
    "os-extended-volumes:volumes_attached": [
        {
            "id": "aaa"
        }
    ]
}

In the original JSON the keys are sorted alphabetically. 在原始JSON中,键按字母顺序排序。 To do that in the cleaned-up JSON, just pass sort_keys=True to json.dumps . 要在清理的JSON中执行此操作,只需将sort_keys=True传递给json.dumps

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ast.literal_eval ValueError(&#39;格式错误的字符串&#39;) - ast.literal_eval ValueError('malformed string') ValueError:使用ast.literal_eval时格式错误的字符串 - ValueError: malformed string when using ast.literal_eval ValueError:使用ast.literal_eval的格式错误的字符串 - ValueError: malformed string using ast.literal_eval 使用ast.literal_eval转换字符串时出错 - Error while converting string using ast.literal_eval 带有元组字符串表示的格式错误的字符串 ValueError ast.literal_eval() - Malformed String ValueError ast.literal_eval() with String representation of Tuple python:ast.literal_eval()提供ValueError:格式错误的字符串 - python: ast.literal_eval() gives ValueError: malformed string ValueError: 格式错误的节点或字符串 ast.literal_eval() - ValueError: malformed node or string with ast.literal_eval() ast.literal_eval() ValueError: 格式错误的节点或字符串 - ast.literal_eval() ValueError: malformed node or string ast.literal_eval() 格式错误的节点或字符串,同时转换带有 array() 列表的字符串 - ast.literal_eval() malformed node or string while converting a string with list of array()s 当我使用 discord.py 使用 ast.literal_eval 时,第 1 行出现格式错误的节点或字符串 - malformed node or string on line 1 when I use ast.literal_eval using discord.py
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM