簡體   English   中英

Python以不同方式解析JSON對象

[英]Python Parse JSON objects in Different Way

我正在處理一個python項目,我們在其中從用戶那里得到一些輸入。 我們實際上正在從事微服務部署。 用戶需要提供以下內容的地方:

1):用戶將提供一個GitHub存儲庫,其中將包括他要部署在特定目錄中的所有微服務。 例如,我們在GitHub存儲庫中有一個目錄結構,如下所示: mysvcs |----nodeservice |----pyservice

2):用戶將提供一個JSON對象,其中將提及此存儲庫的URL以及這些微服務的其他信息,例如:

{
  "repo_url": "https://github.com/arycloud/mysvcs.git",

  "services":[
        {
        "name": "pyservice",
        "routing": {
          "path": "/",
          "service": "pyservice",
          "port": "5000"
        }
      },
      {
        "name": "nodeservice",
        "routing": {
          "path": "/",
          "service": "nodeservice",
          "port": "8080"
        }
      }
        ]
}

然后,我們從GitHub存儲庫中讀取所有服務,並使用它們的目錄來讀取源代碼。與此同時,我們正在解析JSON對象以獲取有關這些服務的一些信息。

我們正在閱讀這樣的倉庫:

tempdir = tempfile.mkdtemp()
saved_unmask = os.umask(0o077)
out_dir = os.path.join(tempdir)
Repo.clone_from(data['repo_url'], out_dir)
list_dir = os.listdir(out_dir)
print(list_dir)
services = []
for svc in range(0, len(data['services'])):
    services.append(list_dir[svc])

print(services)

根據上面的示例,它將返回:

['nodesvc', 'pyservice']

但是,當我們閱讀JSON對象時,用戶以不同的順序而不是按字母順序提及服務,因此當我們使用上述數組遍歷服務時,我們試圖對JSON對象服務和列表使用相同的索引克隆GitHub存儲庫后的目錄,但由於順序不同,它會交換數據。

這是一個示例代碼:

def my_deployment(data):
    # data is JSON object
    # Clone github repo and grab Dockerfiles
    tempdir = tempfile.mkdtemp()
    saved_unmask = os.umask(0o077)
    out_dir = os.path.join(tempdir)
    Repo.clone_from(data['repo_url'], out_dir)
    list_dir = os.listdir(out_dir)
    print(list_dir)
    services = []
    for svc in range(0, len(data['services'])):
        services.append(list_dir[svc])
    print(services)
    for service in range(len(services)):
        # Here i need to use the data from JSON object for current service 
        data['services'][service]['routing']['port']
        # Here it's using the data of **pyservice** instead of **nodeservice** and vice versa.

重要提示 :GitHub中服務的順序為['nodeservices', 'nodeservices']但在JSON對象中,用戶可以以不同的順序提及其服務,例如pyservices, nodeservices 因此,當我們循環瀏覽時,如何同步這兩個源的順序? 這是主要問題。

我已經通過以下方式更改JSON對象的結構來進行嘗試:

"services":[
    "pyservice": {
      "routing": {
        "path": "/",
        "service": "pyservice",
        "port": "5000"
      }
    },
    "nodeservice": {
      "routing": {
        "path": "/node",
        "service": "nodeservice",
        "port": "8080"
      }
    }
]

但是它說syntax is not correct 我該如何克服這個問題?

提前致謝!

JSON無效的原因是,JSON數組中不能包含名稱/值對。 頁面告訴您一個數組可以是:

以逗號分隔的未命名值列表(簡單或復雜),括在方括號中

下面的JSON有什么用嗎?

{
  "repo_url": "https://github.com/arycloud/mysvcs.git",

  "services":[
    {
      "pyservice": {
        "routing": {
          "path": "/",
          "service": "pyservice",
          "port": "5000"
        }
      }
    },
    {
      "nodeservice": {
        "routing": {
          "path": "/node",
          "service": "nodeservice",
          "port": "8080"
        }
      }
    }
  ]
}

如果要按字母順序對services進行排序,可以執行以下操作:

services = data["services"]

b = {}
for node in services:
  b.update(dict(node))

alphabetical_list = sorted(b)

注意:

這為您提供了一個列表['nodeservice', 'pyservice'] ,您可以使用該列表獲取b的對象。

您認為太復雜了。

for svc in data['services']:
    print(svc['name'], svc['routing']['port'])

完成。

一般觀察:您似乎堅持使用循環索引。 別。 Python循環沒有索引是一件好事。

每當你想寫

for thing in range(len(some_list)):

停下來

for thing in some_list:

代替。

在這里,我們可以使用一種方法來解決此訂單同步問題:

首先,默認情況下,GitHub存儲庫中的目錄順序按字母順序排列,因此,如果我們對JSON對象中服務數組的順序進行排序,我們將能夠為兩個源獲得相同的索引。 甚至要確保我們可以按字母順序對這兩個來源進行排序。

代碼如下:首先將JSON對象的services數組排序為:

data['services'] = sorted(data["services"], key=lambda d: d["name"])

通過考慮問題中的示例,它將為我們提供:

services = [
   {"nodeservice": {
     "A": "B"
     }
   },
   {"pyservice":{
     "X": "Y"
    }
   }
]

然后,我們將對GitHub存儲庫中的目錄列表進行排序,如下所示:

Repo.clone_from(data['repo_url'], out_dir)
list_dir = os.listdir(out_dir)
print(list_dir)
services = []
for svc in range(0, len(data['services'])):
    services.append(list_dir[svc])

services.sort()
print(services)

根據上面問題中的示例,它會給我們: ['nodeservice', 'pyservice']

因此,在兩種情況下,我們首先將pyservice nodeservicepyservice ,表示相同的順序。

暫無
暫無

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

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