将带“\”的字符串转换为json或字典d

2024-03-28 16:58:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个csv列数据如下,从上学期的助教说,我们可以导出和导入为json。你知道吗

"""[
    {\""type\"": \""account\"", \""data\"": {\""bid\"": 12, \""acc_num\"": 22}}, 
    {\""type\"": \""card\"", \""data\"": {\""card_num\"": 85}}
]"""

与他所说的不同,我不能在Postgres中用json类型导入它。但我可以将其作为character varyingtext类型导入。在这两种情况下,数据都被提取到一个python字符串中,如下所示。你知道吗

[
    {\type\: \account\, \data\: {\bid\: 12, \acc_num\: 22}},
    {\type\: \card\, \data\: {\card_num\: 85}}
]

考虑到它的原始形式,您认为将其转换为python数据或json数据的有效方法是什么?我试过了

1)用.replace("\\",'\"')\转换成":效果不好,因为有\t\b之类的东西。你知道吗

2)json.loads(string)json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes:错误。我知道我不能这么做,因为它不是一个正确的json表单,但我试过了。你知道吗

(编辑) csv文件中的一行

名称、电话、本地、域、密码、支付、lat、lng

Daivd,01095434668,tfalkc,smh.com.au,8mf3trl,"""[{\""type\"": \""account\"", \""data\"": {\""bid\"": 12, \""acc_num\"": 710831175086172}}, {\""type\"": \""card\"", \""data\"": {\""card_num\"": 8543466885434668}}, {\""type\"": \""card\"", \""data\"": {\""card_num\"": 1221510412215104}}, {\""type\"": \""card\"", \""data\"": {\""card_num\"": 4871213148712131}}]""",37.6274,126.98167 

Tags: csv数据json类型datatypepostgresaccount
2条回答

这是从您发布的内容中获取有效Python对象的一种方法,但我认为可能有更干净、更不容易出错的方法。之后,您可以json.dumps()存储结果。你知道吗

from ast import literal_eval

a = """[
    {\""type\"": \""account\"", \""data\"": {\""bid\"": 12, \""acc_num\"": 22}}, 
    {\""type\"": \""card\"", \""data\"": {\""card_num\"": 85}}
]"""

a = literal_eval(a.replace('\""', '"'))

您可以通过csv模块加载csv(或者使用pandas,即使在这里也可能是多余的)。只是该字段的格式不正确,您必须用literal_eval打开它,但它是一个有效的json字符串:

with open('file.csv') as fd:
    rd = csv.DictReader(fd)
    line = next(rd)   # only read first line here ; loop if you want to read more...
    line = ast.literal_eval(line)
    data = json.loads(line)

如预期所示:

[{'data': {'acc_num': 710831175086172, 'bid': 12}, 'type': 'account'},
 {'data': {'card_num': 8543466885434668}, 'type': 'card'},
 {'data': {'card_num': 1221510412215104}, 'type': 'card'},
 {'data': {'card_num': 4871213148712131}, 'type': 'card'}]

注意:此代码处理问题编辑中给出的示例csv行。你知道吗

相关问题 更多 >