【发布时间】:2018-10-10 06:21:41
【问题描述】:
我正在开发一个 python 项目,我们正在从用户那里获得一些输入。 实际上,我们正在研究微服务部署。其中用户需要提供以下内容:
1):用户将提供一个 GitHub 存储库,其中将包括他想要在特定目录中部署的所有微服务。
例如,我们在 GitHub 存储库中有一个目录结构,如下所示:
mysvcs
|----nodeservice
|----pyservice
2):用户将提供一个 JSON 对象,他将在其中提及此 repo 的 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里的
[]改成{} -
嗨 @shadowtalker,它是 JSON 对象数组。
-
如果你在JSON validator 中运行你的代码,你会发现它是无效的。
-
嗨@VilleKoo,哪一个?我已经发布了 2 个版本的 JSON 对象,第一个是有效的,第二个不是我在问题中提到的。
-
@AbdulRehman 最底层
标签: python json python-3.x jsonparser