【问题标题】:how to parse data from multiple json fields and combine them in one list?如何解析来自多个 json 字段的数据并将它们组合在一个列表中?
【发布时间】:2020-01-01 13:10:50
【问题描述】:

假设我在 json 文件中每个对象有 3 个字段。他们是

[{
    "morning" :   "[0, 1, 4, 6]",
    "afternoon" : "[0, 2, 3, 5, 6]",
    "evening" :   "[1, 4, 6]"
},
    .
    .
    .
{
    "morning" :   "[3, 5, 6]",
    "afternoon" : "[0, 2, 6]",
    "evening" :   "[1, 4, 6]"
}]

在这里, 0 = 星期日,1 = 星期一,. . . . 6 = 星期六

.
我想以这种方式解析 json 文件,而不是 3 个字段(早上、下午、晚上),我将只有一个名为 schedule 的字段,它是 21 个元素的列表。因为我一天有 3 次,一周有 7 天。这给了我数字 21。

我希望最终的结果是这样的,

"schedule" : "[sm, sa, se, mm, ma, me, tm, ta, te, wm, wa, we, thm, tha, the, fm, fa, fe, sam, saa, sae ]"

这里 sm = sunday_morning,ma = monday_afternoon,the = thursday_evening

第一个 OBJ 的输出示例:

"schedule" : [true, true, false, true, false, false, false, true, false, false, true, false, true, false, true, false, true, false, true, true, true]

【问题讨论】:

  • 你尝试了什么,出了什么问题?
  • 有什么原因,为什么列表是strings ("[3, 5, 6]")?
  • 我正在尝试思考算法。我所做的是定义一个包含 21 个元素的列表,并在函数中传递上午、下午、晚上的列表。该函数根据数据插入真或假。

标签: python json parsing


【解决方案1】:

您可以遍历每一天(在本例中为 7 天),然后检查当前日期是否存在于上述数组中(早上、下午和晚上)。如果存在,您可以将true 附加到列表变量中,否则false

您必须检查每个条件,即早上、下午和晚上,以附加每天的可用性。

根据要求,要成功解析 JSON 数据中的 Null(空/无)值,您需要首先检查该字段是否为空。如果它为空,只需附加 false 并继续下一个条件,每个条件为三个时间(早上、下午和晚上)。

根据您的要求,这里有一个示例代码可能会有所帮助:

import json

# Sample JSON Input
input = '{"morning":[],"afternoon":null,"evening":"[1, 4, 6]"}'

jsonInput = json.loads(input)

# Start processing
schedule = []

for x in range(0, 7):

    if jsonInput['morning'] is None:
        schedule.append('false')
    else:
        if str(x) in jsonInput['morning']:
            schedule.append('true')
        else:
            schedule.append('false')
    if jsonInput['afternoon'] is None:
        schedule.append('false')
    else:
        if str(x) in jsonInput['afternoon']:
            schedule.append('true')
        else:
            schedule.append('false')
    if jsonInput['evening'] is None:
        schedule.append('false')
    else:
        if str(x) in jsonInput['evening']:
            schedule.append('true')
        else:
            schedule.append('false')

print(jsonInput)
print(schedule)

【讨论】:

  • 非常感谢您的回答并告诉我如何实时解决这个问题。
  • 面临更多问题。如果上午、下午或晚上的值为空,如何处理?在这种情况下,我想在特定插槽中附加 false
  • null 会用空数组或 null 关键字表示?
  • 我已经更新了我的答案。请检查这是否是您想要的。
猜你喜欢
  • 1970-01-01
  • 2015-12-21
  • 2021-03-06
  • 1970-01-01
  • 2014-06-01
  • 1970-01-01
  • 2022-01-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多