如何使用 simplejson 正确解析 JSON?

发布于 2024-12-12 01:32:40 字数 938 浏览 0 评论 0 原文

我可以有以下 JSON 字符串:

{ "response" : [ [ { "name" : "LA_",
          "uid" : 123456
        } ],
      [ { "cid" : "1",
          "name" : "Something"
        } ],
      [ { "cid" : 1,
          "name" : "Something-else"
        } ]
    ] }

或以下之一:

{"error":"some-error"}

{ "response" : [ [ { "name" : "LA_",
          "uid" : 123456
        } ],
      [ { "cid" : "1",
          "name" : ""
        } ],
      [ { "cid" : 1,
          "name" : "Something-else"
        } ]
    ] }

{ "response" : [ [ { "name" : "LA_",
          "uid" : 123456
        } ] ] }

因此,我不确定是否所有子项和元素都在那里。进行以下验证是否足以获得 Something 值:

if jsonstr.get('response'):
    jsonstr = jsonstr.get('response')[1][0]
    if jsonstr:
        name = jsonstr.get('name')
        if jsonstr: # I don't need empty value
            # save in the database

同样可以简化吗?

I can have the following JSON string:

{ "response" : [ [ { "name" : "LA_",
          "uid" : 123456
        } ],
      [ { "cid" : "1",
          "name" : "Something"
        } ],
      [ { "cid" : 1,
          "name" : "Something-else"
        } ]
    ] }

or one of the following:

{"error":"some-error"}

{ "response" : [ [ { "name" : "LA_",
          "uid" : 123456
        } ],
      [ { "cid" : "1",
          "name" : ""
        } ],
      [ { "cid" : 1,
          "name" : "Something-else"
        } ]
    ] }

{ "response" : [ [ { "name" : "LA_",
          "uid" : 123456
        } ] ] }

So, I am not sure if all childs and elements are there. Will it be enough to do the following verifications to get Something value:

if jsonstr.get('response'):
    jsonstr = jsonstr.get('response')[1][0]
    if jsonstr:
        name = jsonstr.get('name')
        if jsonstr: # I don't need empty value
            # save in the database

Can the same be simplified?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

妥活 2024-12-19 01:32:40

您不能保证每次解析内部对象的顺序都相同,因此索引并不是引用 name 属性设置为 < 的对象索引的安全选择。代码>某事

您无需嵌套所有这些 if 语句,而是可以使用 列表理解。请注意,如果您迭代 response 键,您会得到一个列表列表,每个列表中都有一个字典:

>>> data = {"response":[[{"uid":123456,"name":"LA_"}],[{"cid":"1","name":"Something"}],[{"cid":1,"name":"Something-else"}]]}
>>> [lst for lst in data.get('response')]
[[{'name': 'LA_', 'uid': 123456}], [{'name': 'Something', 'cid': '1'}], [{'name': 'Something-else', 'cid': 1}]]

如果您索引每个列表中的第一项 (lst[0]),您最终会得到一个对象列表:

>>> [lst[0] for lst in data.get('response')]
[{'name': 'LA_', 'uid': 123456}, {'name': 'Something', 'cid': '1'}, {'name': 'Something-else', 'cid': 1}]

如果您随后将 if 条件添加到列表理解中以匹配对象上的 name 属性,您会得到一个列出包含所需对象的单个项目:

>>> [lst[0] for lst in data.get('response') if lst[0].get('name') == 'Something']
[{'name': 'Something', 'cid': '1'}]

然后通过索引最终列表中的第一项,您将获得所需的对象:

>>> [lst[0] for lst in data.get('response') if lst[0].get('name') == 'Something'][0]
{'name': 'Something', 'cid': '1'}

因此您可以将其转换为函数并继续您的生活:

def get_obj_by_name(data, name):
    objects = [lst[0] for lst in data.get('response', []) if lst[0].get('name') == name]
    if objects:
        return objects[0]

    return None

print get_obj_by_name(data, 'Something')
# => {'name': 'Something', 'cid': '1'}

print get_obj_by_name(data, 'Something')['name']
# => 'Something'

并且它应该具有弹性,并且如果 None找不到 >response 键:

print get_obj_by_name({"error":"some-error"}, 'Something')
# => None

You're not guaranteed that the ordering of your inner objects will be the same every time you parse it, so indexing is not a safe bet to reference the index of the object with the name attribute set to Something.

Instead of nesting all those if statements, you can get away with using a list comprehension. Observe that if you iterate the response key, you get a list of lists, each with a dictionary inside of it:

>>> data = {"response":[[{"uid":123456,"name":"LA_"}],[{"cid":"1","name":"Something"}],[{"cid":1,"name":"Something-else"}]]}
>>> [lst for lst in data.get('response')]
[[{'name': 'LA_', 'uid': 123456}], [{'name': 'Something', 'cid': '1'}], [{'name': 'Something-else', 'cid': 1}]]

If you index the first item in each list (lst[0]), you end up with a list of objects:

>>> [lst[0] for lst in data.get('response')]
[{'name': 'LA_', 'uid': 123456}, {'name': 'Something', 'cid': '1'}, {'name': 'Something-else', 'cid': 1}]

If you then add an if condition into your list comprehension to match the name attribute on the objects, you get a list with a single item containing your desired object:

>>> [lst[0] for lst in data.get('response') if lst[0].get('name') == 'Something']
[{'name': 'Something', 'cid': '1'}]

And then by indexing the first item that final list, you get the desired object:

>>> [lst[0] for lst in data.get('response') if lst[0].get('name') == 'Something'][0]
{'name': 'Something', 'cid': '1'}

So then you can just turn that into a function and move on with your life:

def get_obj_by_name(data, name):
    objects = [lst[0] for lst in data.get('response', []) if lst[0].get('name') == name]
    if objects:
        return objects[0]

    return None

print get_obj_by_name(data, 'Something')
# => {'name': 'Something', 'cid': '1'}

print get_obj_by_name(data, 'Something')['name']
# => 'Something'

And it should be resilient and return None if the response key isn't found:

print get_obj_by_name({"error":"some-error"}, 'Something')
# => None
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文