从JSON日志中提取数据

csbfibhn  于 2022-12-01  发布在  其他
关注(0)|答案(1)|浏览(196)

我是一个编程的初学者,我试图从一个JSON日志文件中提取元素,但是我得到了一个错误,我不知道如何处理它。

import json
with open("/Users/milosz/Desktop/logi.json") as f:
    data = json.load(f)
print(type(data['Objects']))
print(data)

for object in data ['Objects']:
    print(object)

错误:

File "/Users/milosz/PycharmProjects/JsonDataExtracter/Program/Python Exracter.py", line 4, in <module>
    print(type(data['Objects']))
TypeError: list indices must be integers or slices, not str

Process finished with exit code 1

我在下面发送日志。

{
    "_id": "635bd4bfc594743ce9b1a5a3",
    "dateStart": "2022-10-28T13:09:28.609Z",
    "dateFinish": "2022-10-28T13:10:23.698Z",
    "method": "customer.file.upsert",
    "request": {
        "Objects": [
            {
                "ERPId": "6915",
                "B24Id": 403772,
                "FileName": "B2B000202",
                "FileContent": "JVBERi0xLjMNJeLjz9MN",
                "B24EntityId": 3334
            }
        ]
bvn4nwqk

bvn4nwqk1#

下面是@accdias提供的指导,它弥补了JSON片段中的不足,并演示了如何访问Objects部分:

import json

json_string = """
{
    "_id": "635bd4bfc594743ce9b1a5a3",
    "dateStart": "2022-10-28T13:09:28.609Z",
    "dateFinish": "2022-10-28T13:10:23.698Z",
    "method": "customer.file.upsert",
    "request": {
        "Objects": [
            {
                "ERPId": "6915",
                "B24Id": 403772,
                "FileName": "B2B000202",
                "FileContent": "JVBERi0xLjMNJeLjz9MN",
                "B24EntityId": 3334
            }
        ]
    }
}
"""
json_dict = json.loads(json_string)
print(json_dict["request"]["Objects"])

输出量:

[{'ERPId': '6915', 'B24Id': 403772, 'FileName': 'B2B000202', 'FileContent': 'JVBERi0xLjMNJeLjz9MN', 'B24EntityId': 3334}]

相关问题