从JSON文件中获取由特定transactionID执行的最后五个事务

时间:2019-06-09 21:56:05

标签: python json list dictionary

我正在编写一个python脚本,该脚本应该从JSON对象获取数据,并且对于名为“ transactionID”的字典键的每个实例,该程序都应该能够返回由特定transactionID执行的最后五个事务。在导入JSON文件,从文件中获取包含'transactionID'字段的字典并将其存储在名为transaction_details的列表中之后,我不确定如何继续。 JSON对象采用以下格式;

[{
    "transactionData":{
                    "transactionID":"tyeeeg5667557", 
                    "deviceID": "uasjaslsa", 
                    "IMEI":"ssjdjdssd", 
                    "transactionDate": "12-12-2019", 
                    "time": "11:40", 
                    "accountDetails": {"userID": "kilopol", "creationdate": "21-12-2019"}, 
                    "Amount": {"amount": 2000, "units": "UGX", "qty":1}, 
                    "paymentMethod": {"name": "mobile money"}, 
                    "productdetails": {"productid": "12jfjf", "name": "airtime", "units":"UGX"}
                    },
"locationdetails": {"address":"Ntinda-Kampala", "street": "Chwa 2 Ntinda-Nakawa"},
"api key": "a9dd1d0f-a605-499a-9618-c449065d34bb", 
"callbackUrl": "http://clinet.com/method", 
"clientid": "5ce7baf3ffd59f2633ed64a3", 
"receptiontime": 1559297122942
},
{
    "transactionData":{
                    "transactionID":"yetrw5667557", 
                    "deviceID": "uweyjaslsa", 
                    "IMEI":"ssycvjdssd", 
                    "transactionDate": "12-12-2019", 
                    "time": "11:40", 
                    "accountDetails": {"userID": "kimange", "creationdate": "21-12-2019"}, 
                    "Amount": {"amount": 4000, "units": "UGX", "qty":2}, 
                    "paymentMethod": {"name": "airtel money"}, 
                    "productdetails": {"productid": "12jfjf", "name": "airtime", "units":"UGX"}
                    },
"locationdetails": {"address":"Kamwokya-Kampala", "street": "Chwa 2 Ntinda-Nakawa"},
"api key": "a9dd1d0f-a605-499a-9618-c449065d34bb", 
"callbackUrl": "http://clinet.com/method", 
"clientid": "5ce7bafutwf2633ed64a3", 
"receptiontime": 1559297122942
},
{
    "transactionData":{
                    "transactionID":"tyeeeg5667557", 
                    "deviceID": "uweyjaslsa", 
                    "IMEI":"ssycvjdssd", 
                    "transactionDate": "12-12-2019", 
                    "time": "11:40", 
                    "accountDetails": {"userID": "kimange", "creationdate": "21-12-2019"}, 
                    "Amount": {"amount": 4000, "units": "UGX", "qty":2}, 
                    "paymentMethod": {"name": "airtel money"}, 
                    "productdetails": {"productid": "12jfjf", "name": "airtime", "units":"UGX"}
                    },
"locationdetails": {"address":"Kamwokya-Kampala", "street": "Chwa 2 Ntinda-Nakawa"},
"api key": "a9dd1d0f-a605-499a-9618-c449065d34bb", 
"callbackUrl": "http://clinet.com/method", 
"clientid": "5ce7bafutwf2633ed64a3", 
"receptiontime": 1559297122942
},
{
"transactionData":{
                    "transactionID":"tyeeeg5667557", 
                    "deviceID": "uasjaslsa", 
                    "IMEI":"ssjdjdssd", 
                    "transactionDate": "12-12-2019", 
                    "time": "11:40", 
                    "accountDetails": {"userID": "kilopol", "creationdate": "21-12-2019"}, 
                    "Amount": {"amount": 2000, "units": "UGX", "qty":1}, 
                    "paymentMethod": {"name": "mobile money"}, 
                    "productdetails": {"productid": "12jfjf", "name": "airtime", "units":"UGX"}
                    },
"locationdetails": {"address":"Gulu", "street": "Burton Street"},
"api key": "a9dd1d0f-a605-499a-9618-c449065d34bb", 
"callbackUrl": "http://clinet.com/method", 
"clientid": "5ce7baf3ffd59f2633ed64a3", 
"receptiontime": 1559297122942
},
{
"transactionData":{
                    "transactionID":"tyeeeg5667557", 
                    "deviceID": "uasjaslsa", 
                    "IMEI":"ssjdjdssd", 
                    "transactionDate": "12-12-2019", 
                    "time": "11:40", 
                    "accountDetails": {"userID": "kilopol", "creationdate": "21-12-2019"}, 
                    "Amount": {"amount": 2000, "units": "UGX", "qty":1}, 
                    "paymentMethod": {"name": "mobile money"}, 
                    "productdetails": {"productid": "12jfjf", "name": "airtime", "units":"UGX"}
                    },
"locationdetails": {"address":"Ntinda-Kampala", "street": "Chwa 2 Ntinda-Nakawa"},
"api key": "a9dd1d0f-a605-499a-9618-c449065d34bb", 
"callbackUrl": "http://clinet.com/method", 
"clientid": "5ce7baf3ffd59f2633ed64a3", 
"receptiontime": 1559297122942
},
{
"transactionData":{
                    "transactionID":"ygdras557", 
                    "deviceID": "uasjaslsa", 
                    "IMEI":"ssjdjdssd", 
                    "transactionDate": "12-12-2019", 
                    "time": "11:40", 
                    "accountDetails": {"userID": "kilopol", "creationdate": "21-12-2019"}, 
                    "Amount": {"amount": 2000, "units": "UGX", "qty":1}, 
                    "paymentMethod": {"name": "mobile money"}, 
                    "productdetails": {"productid": "12jfjf", "name": "airtime", "units":"UGX"}
                    },
"locationdetails": {"address":"Ntinda-Kampala", "street": "Chwa 2 Ntinda-Nakawa"},
"api key": "a9dd1d0f-a605-499a-9618-c449065d34bb", 
"callbackUrl": "http://clinet.com/method", 
"clientid": "5ce7baf3ffd59f2633ed64a3", 
"receptiontime": 1559297122942
},
{
    "transactionData":{
                    "transactionID":"tyeeeg5667557", 
                    "deviceID": "uasjaslsa", 
                    "IMEI":"ssjdjdssd", 
                    "transactionDate": "7-7-2019", 
                    "time": "11:40", 
                    "accountDetails": {"userID": "kilopol", "creationdate": "21-12-2019"}, 
                    "Amount": {"amount": 6700, "units": "UGX", "qty":1}, 
                    "paymentMethod": {"name": "mobile money"}, 
                    "productdetails": {"productid": "12jfjf", "name": "airtime", "units":"UGX"}
                    },
"locationdetails": {"address":"Ntinda-Kampala", "street": "Chwa 2 Ntinda-Nakawa"},
"api key": "a9dd3d9f-a605-499a-9618-c449065d34bb", 
"callbackUrl": "http://clinet.com/method", 
"clientid": "5ce7baf3ffd59f2633ed64a3", 
"receptiontime": 1559297122942
}
]

从下面的代码开始,从创建一个名为transaction_details的列表以保存包含transactionID键的字典的位置开始,我需要一些有关如何实现此功能的帮助。

from pymongo import MongoClient
import json


class ExtractData(object):
    def __init__(self, file):
        self.file = file

    def obtainLastFiveTransactions(self):
        client = MongoClient('localhost', 27017)
        database = client['database']
        collection = database['collection']

        with open(self.file) as f_obj:
            data_file = json.load(f_obj)
            collection.insert_many(data_file)
            data_received = collection.find({})

            for dict_data in data_received:
                for key, value in dict_data.items():
                    if key == 'transactionData':
                        transactionDataValues = value
                        transaction_details = []
                        for key, value in transactionDataValues.items():
                            if key == 'transactionID':
                                transaction_details.append(transactionDataValues)

1 个答案:

答案 0 :(得分:1)

可能不是最有效的解决方案,但是此代码片段读取json,创建一个包含transactionIds作为键的字典,然后将5个按transactionDate排序的最新事务追加到字典中。

对于所有transactionId:

import json
from datetime import datetime

transaction_dict = {}

with open(json_file) as f_obj:
    data = json.load(f_obj)

    # Sort list of transactions by transactionDate
    data_sorted = sorted(
        data,
        key=lambda k: datetime.strptime(k['transactionData']['transactionDate'], "%d-%m-%Y").timestamp(),
        reverse=True
)

    # Make a dictionary with transactionIds as keys
    for transaction in data_sorted:
        transactionId = transaction['transactionData']['transactionID']
        transaction_dict[transactionId] = []

    # Append the 5 newest transaction for appropriate key
    for transaction in data_sorted:
        transactionId = transaction['transactionData']['transactionID']
        if len(transaction_dict[transactionId]) < 6:
            transaction_dict[transactionId].append(transaction)

对于特定交易:

import json
from datetime import datetime

transaction_key = 'xxxx'
transaction_dict = {
    transaction_key: []
}

transactions = []

with open(json_file) as f_obj:
    data = json.load(f_obj)

    for transaction in data:
        if transaction['transactionData']['transactionID'] == transaction_key:
            transactions.append(transaction)

    # Sort list of transactions by transactionDate
    data_sorted = sorted(
        transactions,
        key=lambda k: datetime.strptime(k['transactionData']['transactionDate'], "%d-%m-%Y").timestamp(),
        reverse=True
    )

    # Append the 5 newest transaction for appropriate key
    for transaction in transactions:
        if len(transaction_dict[transaction_key]) < 6:
            transaction_dict[transaction_key].append(transaction)

希望这会有所帮助!