如何正确比较 Python 中的 2 JSON 请求响应字符串

How to properly compare 2 JSON request response strings in Python

我想比较 2 个 Python 响应字符串并打印出差异,这是我现在的代码:

导入请求 导入 json 导入时间

getFirst = requests.get("https://api-mainnet.magiceden.dev/v2/collections?offset=0&limit=1") liveRN = json.dumps(getFirst.json(), indent=4)

虽然正确: get = requests.get("https://api-mainnet.magiceden.dev/v2/collections?offset=0&limit=1") dataPretty = json.dumps(get.json(), 缩进=4) 数据 = get.json()

if get.status_code == 200:
    print("ok")
if dataPretty != data:
    for item in data:
        if str(item) not in liveRN:
            send = 1
            print(f"Found difference: {item}")

            symbol = item['symbol']
            img = item['image']
            name = item['name']
            description = item['description']

            print(symbol)
            print(img)
            print(name)
                         
        else:
            print("Didnt find")
else:
    print("No change")

time.sleep(15)

我只想在两个响应不匹配时打印项目,但现在即使字符串匹配,它也会打印我想要的项目。

我试图查看添加另一个 if 条件,如果 2 个请求响应匹配,它不会做任何事情,只是通过,但没有用

您可以使用sets 来查找字典中的项目是否被更改。我使用了 another question 中的比较代码,但这在某种程度上可以用于解决您的问题

import requests 
import time

def dict_compare(d1, d2):
    d1_keys = set(d1.keys())
    d2_keys = set(d2.keys())
    shared_keys = d1_keys.intersection(d2_keys)
    added = d1_keys - d2_keys
    removed = d2_keys - d1_keys
    modified = {o : (d1[o], d2[o]) for o in shared_keys if d1[o] != d2[o]}
    same = set(o for o in shared_keys if d1[o] == d2[o])
    return added, removed, modified, same

first = requests.get("https://api-mainnet.magiceden.dev/v2/collections?offset=0&limit=1").json()[0]

while True: 
    get_second = requests.get("https://api-mainnet.magiceden.dev/v2/collections?offset=0&limit=1")

    if get_second.status_code == 200:
        print("ok")

    second = get_second.json()[0]
    added, removed, modified, same = dict_compare(first, second)

    if len(added) > 0 or len(modified) > 0  or len(removed) > 0:
        print("added: ", added)
        print("modified: ", modified)
        print("removed: ", removed)
    else:
        print("No change")
        
    time.sleep(15)