簡體   English   中英

在 Python 中生成 JSON 模式

[英]Generate JSON schema in Python

我正在從事一個從 Web 服務中提取數據的項目。 我想分析我從這些不同的調用中得到的 JSON 響應,這樣我就可以理解我得到的響應的結構。

例如,查看此響應提供的 json: https : //jsonplaceholder.typicode.com/users

我希望生成此響應的“架構”或骨架,如下所示:

[
  {
    "id": "Number",
    "name": "String",
    "username": "String",
    "email": "String",
    "address": {
      "street": "String",
      "suite": "String",
      "city": "String",
      "zipcode": "String",
      "geo": {
        "lat": "Number",
        "lng": "Number"
      }
    },
    "phone": "String",
    "website": "String",
    "company": {
      "name": "String",
      "catchPhrase": "String",
      "bs": "String"
    }
]

有誰知道我可以通過現有的標准模塊或第 3 方模塊實現這一目標的方法嗎? 我已經做了大量的搜索,但沒有任何運氣。

在此先感謝您的任何建議。

我不知道有一種簡單的方法可以使用現有的標准或第 3 方模塊獲得所需的數據結構。

就像一個想法 - 因為沒有其他回復 - 您可以嘗試類似於以下內容,但要更加小心地遍歷嵌套字典:

for i in range(len(json_parsed)):
    for k,v in json_parsed[i].items():
        print(k, str(type(v)).replace("<class", "").replace('>',""))

    id  'int'
    username  'str'
    website  'str'
    address  'dict'
    email  'str'
    phone  'str'
    company  'dict'
    name  'str'
    id  'int'
    username  'str'
    website  'str'
    address  'dict'
    email  'str'
    phone  'str'
    company  'dict'
    name  'str'

這是部分解決方案。 它翻閱了一本 Python 字典,當你這樣做時你得到的那種:

data = requests.get(...)
results = data.json()

我仍在研究它,即深入檢查列表的復雜元素是否相同,以便我可以返回第first...而不是first, second

這是代碼:

def schema(d, spacer='  ', indent=0, force=0):
    types = [list, set, dict, tuple]
    open_symbols = ['[', '{', '{', '(']
    close_symbols = [']', '}', '}', ')']
    res = ''
    typ = type(d)
    if typ in types:
        os, cs = list(zip(open_symbols, close_symbols))[types.index(typ)]
        res += f'{spacer * (indent*force)}{os}\n'
        if isinstance(d, dict):
            for key, value in d.items():
                res += f'{spacer * (indent+1)}{key}: '
                res += f'{schema(value, spacer, indent+1)}\n'
        else:
            if(typ is set):
                return res[:-1] + (d.pop().__class__.__name__ if len(d) else None) + cs
            else:
                if all(isinstance(x, type(d[0])) for x in d[1:]) and type(d[0]) not in types:
                    return res[:-1] + d[0].__class__.__name__ + cs
                else:
                    for value in d:
                        res += f'{schema(value, spacer, indent+1, 1)}\n'
        res += f'{spacer * indent}{cs}'
    else:
        res = d.__class__.__name__
    return res

乍一看,很明顯:

  1. 這是從我自己的pprint版本派生出來的,所以你有間距元素; 我不喜歡pprint的輸出;
  2. 這並不是 JSON 結果所獨有的,這就是您在其中找到settuple的原因; 沒有考慮許多其他結構化類型;
  3. 這將返回一個str ,因此您可以像這樣使用它: print(schema(d)) ,其中d是某個 Python 變量;
  4. 有工作要做,即所有這些return

我希望這會有所幫助,經過這么多年。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM