简体   繁体   中英

Identify the nested object with min value in a JSON array

I have a JSON file with the following structure.

I want to identify the channel with the minimum fee and to print its details (channel_id, node1, node2 and the total fee)

The total fee of a channel is the sum of fees of both nodes: total_fee = fee_node1 + fee_node2

{
"edges": [
    {
        "channel_id": "1",
        "node1": "Alice",
        "node2": "Bob",
        "node1_policy": {
            "fee": "1000"
        },
        "node2_policy": {
            "fee": "1000"
        }
    },
    {
        "channel_id": "2",
        "node1": "Caleb",
        "node2": "Daniel",
        "node1_policy": {
            "fee": "500",
        },
        "node2_policy": {
            "fee": "3000",
        }
    },
    {
        "channel_id": "3",
        "node1": "Elen",
        "node2": "Fatih",
        "node1_policy": {
            "fee": "2000"
        },
        "node2_policy": {
            "fee": "5000"
        }
    }

}

What is the best method to accomplish this task?

It is quite simple to do that in a few lines of code. I should mention though that the format of your JSON file is invalid, because of the redundant commas right after the fee keys. Consider removing them in order to be valid:

import json

with open('channels.json', 'r') as inFile:
    jsonData = json.loads(inFile.read())
    minimum = min([elem for elem in jsonData['edges']], key=lambda e: int(e['node1_policy']['fee']) + int(e['node2_policy']['fee']))
    print(minimum)

Output:

{'channel_id': '1', 'node1': 'Alice', 'node2': 'Bob', 'node1_policy': {'fee': '1000'}, 'node2_policy': {'fee': '1000'}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM