在单行中将 JSON 嵌套数组转换为 Python 嵌套列表
Convert JSON nested array to Python nested list in one-liner
我想使用单行 Python 方法将 JSON 嵌套数组转换为 Python 嵌套列表。
下面是我的 JSON 嵌套数组的示例:
my_dict = {
"background": "This is a test text.",
"person": [
{"name": "Max", "tranx_info": [
{"tranx_date":"7/1/2020","amount": 82 },
{"tranx_date":"27/2/2017","amount":177 }]
},
{"name": "Lily", "tranx_info": [
{"tranx_date":"12/7/1989","amount": 165 },
{"tranx_date":"28/2/1998","amount": 200 },
{"tranx_date":"28/2/2098","amount": 34 }]
}
]
}
我假设这将是 Python 中的嵌套列表理解?到目前为止我已经尝试过但我只能将结果放入列表中:
tranx_date_result = [x["tranx_date"] for y in my_dict["person"] for x in y["tranx_info"]]
#output
>>> ["7/1/2020","27/2/2017","12/7/1989","28/2/1998","28/2/2098"]
我希望我的 "tranx_date"
结果在嵌套列表中;像这样:
tranx_date_result = [["7/1/2020","27/2/2017"],["12/7/1989","28/2/1998","28/2/2098"]]
感谢任何帮助:)
只需使用嵌套列表理解:
>>> [[x["tranx_date"] for x in y["tranx_info"]] for y in my_dict["person"]]
[['7/1/2020', '27/2/2017'], ['12/7/1989', '28/2/1998', '28/2/2098']]
我想使用单行 Python 方法将 JSON 嵌套数组转换为 Python 嵌套列表。
下面是我的 JSON 嵌套数组的示例:
my_dict = {
"background": "This is a test text.",
"person": [
{"name": "Max", "tranx_info": [
{"tranx_date":"7/1/2020","amount": 82 },
{"tranx_date":"27/2/2017","amount":177 }]
},
{"name": "Lily", "tranx_info": [
{"tranx_date":"12/7/1989","amount": 165 },
{"tranx_date":"28/2/1998","amount": 200 },
{"tranx_date":"28/2/2098","amount": 34 }]
}
]
}
我假设这将是 Python 中的嵌套列表理解?到目前为止我已经尝试过但我只能将结果放入列表中:
tranx_date_result = [x["tranx_date"] for y in my_dict["person"] for x in y["tranx_info"]]
#output
>>> ["7/1/2020","27/2/2017","12/7/1989","28/2/1998","28/2/2098"]
我希望我的 "tranx_date"
结果在嵌套列表中;像这样:
tranx_date_result = [["7/1/2020","27/2/2017"],["12/7/1989","28/2/1998","28/2/2098"]]
感谢任何帮助:)
只需使用嵌套列表理解:
>>> [[x["tranx_date"] for x in y["tranx_info"]] for y in my_dict["person"]]
[['7/1/2020', '27/2/2017'], ['12/7/1989', '28/2/1998', '28/2/2098']]