【问题标题】:json.loads() not converting into dictjson.loads() 没有转换成字典
【发布时间】:2021-09-08 01:39:24
【问题描述】:

我在从表中的 json 字符串中解析特定键时遇到问题。下面是我读取 csv 文件并从每行的 json 列中提取“employee_id”的代码:

with open('data.csv') as csvFile:
    csv_reader = csv.reader(csvFile, delimiter=',')
    next(csv_reader, None)  # skips the header row

for row in csv_reader:
    event_data = row[4]
    data = json.loads(event_data)
    print(data['employee_id'])

这是一个示例 event_data 输出:

"{\"py/object\": \"employee_information.event_types.EmployeeCreated\", \"employee_id\": \"98765\", \"employee_first_name\": \"Jonathan\", \"employee_last_name\": \"Smith\", \"application_id\": \"1234\", \"address\": \"1234 street\"}"

但我收到一条错误消息:

Traceback (most recent call last):
  File "/Users/user/Documents/python_test/main.py", line 14, in <module>
    print(data['employee_id'])
TypeError: string indices must be integers

我检查了数据的类型,它返回了一个 str。我认为 json.loads 是假设将 json 字符串转换为 python dict?

【问题讨论】:

  • event_data 是一个字符串,这意味着您的 JSON 数据包含在引号中。

标签: python json


【解决方案1】:

event_data 出于某种原因被双重编码,因此您需要对其进行两次解码。

data = json.loads(json.loads(event_data))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-19
    相关资源
    最近更新 更多