使用ast.literal_eval时字符串格式错误 [英] Malformed string while using ast.literal_eval

查看:73
本文介绍了使用ast.literal_eval时字符串格式错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用json转储,然后将json加载到同一数据上.数据是unicode,所以我将其转换为字符串.我使用ast.literla_eval尝试获取要判断的字符串类型,但出现错误格式错误的字符串.

I used json dump and then json load on the same data. The data is unicode so I converted it to string. Using the ast.literla_eval I tried to get the type of the string to dict but I am getting error Malformed String.

json加载的输出低于

output of json load is below

('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'>)

我尝试了什么?

        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

我希望输出成为字典,但我没有得到.另外,json加载提供了unicode数据,因此我相信new_data = data.encode('utf-8')是多余的.但是,如果我使用ast.literal_eval而不进行编码,则会出现格式错误的字符串错误.无论如何,我无法将数据类型设置为字典.

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. But if I use ast.literal_eval without encoding I get Malformed string error. In any case, I am not able to get the data type to be dictionary.

错误:

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

json转储前的数据:

The data before json dump :

"{\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}"

推荐答案

check_output返回的数据已经是JSON,因此您应该使用json.dump再次对其进行JSON验证.您可以按原样将其写入文件,该文件将是有效的JSON文件.您可以使用json.loads将其加载到Python对象中:

That data returned by check_output is already JSON, so you should not JSON-ify it again with json.dump. You can just write it to the file as is, and the file will be a valid JSON file. And you can load it into a Python object with json.loads:

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)

输出

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

如果要使其成为纯净的JSON,请将该Python对象传递给json.dumpjson.dumps

And if you want to make it into clean JSON, pass that Python object to json.dump or json.dumps

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

输出

{
    "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"
        }
    ]
}

在原始JSON中,键是按字母顺序排序的.要在清理后的JSON中执行此操作,只需将sort_keys=True传递给json.dumps.

In the original JSON the keys are sorted alphabetically. To do that in the cleaned-up JSON, just pass sort_keys=True to json.dumps.

这篇关于使用ast.literal_eval时字符串格式错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆