使用python,我想根据transactionTypeName中的“transacations.details”将一个json文件分割成多个文件。在每个文件中,我希望从照顾者到用户名开始提供其余的详细信息。下面是json文件。必须清理这些价值。在密码方面需要帮助。提前谢谢。
我知道如何使用json.loads读取json节点。但不知道该怎么分手。
{
"careperson": {
"FirstName": "tryy",
"LastName": "dbdfb"
},
"activityDate": "2000-06-14T15:35:00",
"locationAddress": {
"Address1": "123g hrtjrtt",
"City": "Turrty",
"State": "AF",
"Zip": "56577"
},
"siteName": "Trwtyjj",
"transactions": [
{
"details": [
{
"expiration": "2002-08-03T23:59:59",
"to_sitelocationId": 0
}
],
"transactionType": 6,
"transactionTypeName": "Can"
},
{
"details": [
{
"expiration": "2002-08-03T23:59:59",
"to_sitelocationId": 0
}
],
"transactionType": 6,
"transactionTypeName": "Worm"
},
{
"details": [
{
"expiration": "2002-08-03T23:59:59",
"to_sitelocationId": 0
}
],
"transactionType": 6,
"transactionTypeName": "Use"
}
],
"sbscrberId": 3344,
"sbscrber": "sdg"
}
我想让它像这样分开。基本上,“可以”、“蠕虫”和“使用”将是单独的文件。下面是“蠕虫”的预期输出。"Can“和"Use”看起来类似。在本例中,有3个transactionTypes,但是可以为其他文件提供更多内容,所以我想使它成为动态的。
{
"careperson": {
"FirstName": "tryy",
"LastName": "dbdfb"
},
"activityDate": "2000-06-14T15:35:00",
"locationAddress": {
"Address1": "123g hrtjrtt",
"City": "Turrty",
"State": "AF",
"Zip": "56577"
},
"siteName": "Trwtyjj",
"transactions": [
{
"details": [
{
"expiration": "2002-08-03T23:59:59",
"to_sitelocationId": 0
}
],
"transactionType": 6,
"transactionTypeName": "Worm"
}
],
"sbscrberId": 3344,
"sbscrber": "sdg"
}
发布于 2022-07-08 21:09:37
正如Kevin所说,循环处理每一笔交易是最好的。这一进程将是:
通过每个transaction.
这可以通过将从文件读取的JSON复制到一个临时对象来简化。
在Python 3中,如下所示(添加了注释来解释每一步):
import json
# Load JSON data from a file into object
fileRead = open('test.json', 'r')
jsonContent = json.load(fileRead)
fileRead.close()
# Loop through each transaction read from the file (3 in the example)
for transaction in jsonContent['transactions']:
jsonFileContent = {}
# Loop through each json key value pair read from the object.
for key, value in jsonContent.items():
if key == 'transactions':
# Override 'transactions' key with the single value that was generated from the first loop
# Initialize empty List
jsonFileContent["transactions"] = []
# Add Transaction to list
jsonFileContent["transactions"].append(transaction)
else:
# Write key value pair to a temporary object
jsonFileContent[key] = value
# Write all contents to file a file 'transactionTypeName'.json (e.g. 'can.json')
fileWrite = open(jsonFileContent['transactions'][0]['transactionTypeName']+'.json', 'w')
json.dump(jsonFileContent, fileWrite)
fileWrite.close()
https://stackoverflow.com/questions/72913506
复制相似问题