首页 > 解决方案 > 对 JSON 文件进行排序以检索元素

问题描述

我正在尝试编写一个读取 json 文件外部的代码,data.json它将输出它的外部。[RSI, MOM, MOM_RSI]以及所有三个部分的总小节。每个小节包含TradingPair and Status. 有没有办法我可以通过最好使用列表理解或不使用 for 循环来做到这一点for data in [RSI, MOM, MOM_RSI]

代码:

def reading(): 
    with open('data.json') as f:
        data = json.load(f)
    return data
reading()

JSON文件:

{
    "RSI": [
      {
        "TradingPair": "BTCUSD",
        "Status": "ACTIVE",
      }
    ],
    "MOM":[
        {
            "TradingPair": "BCHUSDT",
            "Status": "PAUSED",
        },
        {
            "TradingPair": "ETHUSDT",
            "Status": "ACTIVE",
        }
    ],
    "MOM_RSI":[
        {
            "TradingPair": "BCHUSDT",
            "Status": "PAUSED",
        },
        {
            "TradingPair": "BTCUSDT",
            "Status": "ACTIVE",
        }
    ]
}

标签: pythonjsonpython-3.xfunctiondictionary

解决方案


这将遍历 JSON 文件并获取小节数和项目列表

变量data必须是您导入的 JSON 文件

subsections = 0 #stores the number of subsections
keys = [] #array to store list of items

for key in data:
    if isinstance(data[key], list): #check if the item is a list
        keys.append(key) #add the item to the list of items
    if len(data[key]) > 0: #check if the item has a length
        subsections += len(data[key]) #add the lenght/number of items to the subsections counter

sections = ','.join(keys) #creates a new string with the items in the keys array
print(sections)
print("Total subsections:", subsections)

使用您的代码完成示例:

def reading(): 
    with open('data.json') as f:
        data = json.load(f)
        subsections = 0 #stores the number of subsections
        keys = [] #array to store list of items
       
        for key in data:
            if isinstance(data[key], list): #check if the item is a list
                keys.append(key) #add the item to the list of items
            if len(data[key]) > 0: #check if the item has a length
                subsections += len(data[key]) #add the lenght/number of items to the subsections counter
        
        sections = ','.join(keys) #creates a new string with the items in the keys array
        print(sections)
        print("Total subsections:", subsections)
reading()

推荐阅读