Python:无法将json格式dict值放入列表

问题描述

我试图从json输入中提取一组日期值。当我完成F_Date提取时,它是正确的。

2020-05-20T00:00:00
2020-05-18T00:00:00
2020-05-15T00:00:00
2020-05-13T00:00:00

我设置了一个包含值的列表,所以我想使用List[0]之类的列表索引来获取列表中的第一个值或列表中的其他值,以作进一步的用途。但是,它失败了。它给了我第一列人物。如果我尝试使用List[1],它会给我一列0而不是2020-05-18T00:00:00,这正是我想要的。任何想法我的代码有什么问题吗?我对现在F_Date是什么类型感到困惑,它不是列表吗?

谢谢。

F_Date = []
for cell in json["Cells"]:
    if cell["ColumnName"] == "T":
        if cell["RowIndex"] + 1 > 9:
            F_Date = cell["displayValue"]
            print(F_Date[0])


output:
2
2
2
2

Json:

json =    {
            "SheetName": "price","SheetIndex": 4,"Cells": [
                {
                    "ColumnName": "T","RowName": "10","Address": "T10","ColumnIndex": 19,"RowIndex": 9,"Value": "2020-05-20T00:00:00","displayValue": "2020-05-20T00:00:00","ValueType": "Date"
                },{
                    "ColumnName": "U","Address": "U10","ColumnIndex": 20,"Value": 2.75,"displayValue": 2.75,"ValueType": "Numeric"
                },{
                    "ColumnName": "V","Address": "V10","ColumnIndex": 21,"Value": 2.15,"displayValue": 2.15,{
                    "ColumnName": "T","RowName": "11","Address": "T11","RowIndex": 10,"Value": "2020-05-18T00:00:00","displayValue": "2020-05-18T00:00:00","Address": "U11","Address": "V11","RowName": "12","Address": "T12","RowIndex": 11,"Value": "2020-05-15T00:00:00","displayValue": "2020-05-15T00:00:00","Address": "U12","Address": "V12","RowName": "13","Address": "T13","RowIndex": 12,"Value": "2020-05-13T00:00:00","displayValue": "2020-05-13T00:00:00","ValueType": "Date"
                }
        ]}

解决方法

您需要做的只是打印F_Date而不是F_Date [0],后者仅打印第一个字符,因为字符串可以解释为字符列表,并且您正在打印索引0。

print(F_Date)

如果您对F_Date是什么感到困惑,则F_Date是您的日期字符串,因为它是您所获得的字典中键的值。

F_Date = []
for cell in json["Cells"]:
    if cell["ColumnName"] == "T":
        if cell["RowIndex"] + 1 > 9:
            F_Date = cell["DisplayValue"] # Here you set F_Date to the value 
            print(F_Date[0])

我认为您要做的是

F_Date = []
for cell in json["Cells"]:
    if cell["ColumnName"] == "T":
        if cell["RowIndex"] + 1 > 9:
            F_Date.append(cell["DisplayValue"]) 
            print(cell["DisplayValue"])