使用python,我想根据"transactionTypeName"将json文件拆分为多个文件。在事务细节中。在每个文件我也希望其他的细节从careperson用户名。下面是json文件。必须清理值。需要帮助与代码。提前谢谢。
我有一些想法如何读取json节点使用json.loads。但不知道怎么分。
{
"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"
}
我想让它像这样分开。基本上,"不能","不行";和";Use"将是单独的文件。下面是" wor& quot;的预期输出。"Can"one_answers";Use"看起来很相似。在这个例子中,有3个transactiontype但其他文件可以有更多所以我想把它改成dynamic
{
"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"
}
正如Kevin所说,遍历每个事务是最好的。这个过程是:
- 遍历每个事务。
- 记录每个键值对到一个临时JSON对象
- 覆盖'transactions'键,只包含一个事务对象。
- 使用'json将临时对象写入文件。将JSON对象写入文件。然后循环直到所有事务都被分割。
这可以通过将从文件读取的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()