我有一个JSON文件,我想将该JSON数据作为键,值对进行处理。
这是我的JSON文件
```"users" : {
"abc": {
"ip": "-------------",
"username": "users@gmail.com",
"password": "---------",
"displayname": "-------",
"Mode": "-----",
"phonenumber": "1********1",
"pstndisplay": "+1 *******5"
},
"efg": {
"ip": "-------------",
"username": "user1@gmail.com",
"password": "---------",
"displayname": "-------",
"Mode": "-----",
"phonenumber": "1********1",
"pstndisplay": "+1 *******5"
},
"xyz": {
"ip": "-------------",
"username": "user2@gmail.com",
"password": "---------",
"displayname": "-------",
"Mode": "-----",
"phonenumber": "1********1",
"pstndisplay": "+1 *******5"```
在这里我尝试获取json数据
``` ${the file as string}= Get File ${users_json_path}
${parsed}= Evaluate json.loads("""${the file as string}""") json
${properties}= Set Variable ${parsed["users"]}
Log ${properties}
:FOR ${key} IN @{properties}
\ ${sub dict}= Get From Dictionary ${properties} ${key}
\ Log ${sub dict}
\ Signin ${sub dict}[ip] ${sub dict}[username] ${sub dict}[password] ${sub dict}[Mode]
\ Log ${key} is successfully signed in.
预期的行为-我正在解析的键应该从JSON文件开始按顺序排列。例如,abc首先登录,然后efg和xyz。
${key} = abc
${key} = efg
${key} = xyz
以下是问题: 1)我们如何按顺序从JSON吸引用户?现在随机 2)什么是实现这一目标的最佳逻辑?
答案 0 :(得分:0)
#!/usr/bin/env python3
import json
def main():
json_str = """
{
"users" : {
"abc": {
"ip": "-------------",
"username": "users@gmail.com",
"password": "---------",
"displayname": "-------",
"Mode": "-----",
"phonenumber": "1********1",
"pstndisplay": "+1 *******5"
},
"efg": {
"ip": "-------------",
"username": "user1@gmail.com",
"password": "---------",
"displayname": "-------",
"Mode": "-----",
"phonenumber": "1********1",
"pstndisplay": "+1 *******5"
}
}
}
"""
json_object = json.loads(json_str)
for line in json_str.split('\n'):
if '"' in line and ':' in line and '{' in line and '"users"' not in line:
key = line.split('"')[1]
print(key, json_object['users'][key])
答案 1 :(得分:0)
我看到您用python 2.7标记了这个问题-Bryan Oakely的注释完全正确,元素按随机顺序排列。
但是,如果您升级到python 3,则从v3.6开始,字典将保证保留插入顺序。因此,使用json库进行解析时,结果将与源字符串/文件中的结果相同。
或者,在v2中,您可以使用OrderedDict完成相同的操作-另外,将JSONDecoder的参数object_pairs_hook
指定为-您基本上会指定结果为{{ 1}}:
OrderedDict