无法遍历 JSON。

huangapple go评论70阅读模式
英文:

Unable to iterate through a json

问题

I have a json object that looks something like this:

[{'"p"': '"{"n":"s","i":"1"}"},.....]

Just imagine multiple objects like this. I want to iterate through this and access n and i keys like a normal JSON but unfortunately, I am not able to figure it out.

I tried this:

for i in a:
    for j in i:
        j.replace('"', ' ')
        for k, v in j:
            print(k, v)

But getting this:

ValueError: not enough values to unpack (expected 2, got 1)

Is there any way I can convert that weird JSON into normal JSON like below:

[{'p': {'n':'s','i':'1'}},.....]

Any help will be appreciated. Thank you.

英文:

I have a json object that looks something like this

[{'"p"': '{"n":"s","i":"1"}'},.....]

Just imagine multiple objects like this. I want to iterate through this and access n and i keys like a normal json but unfortunately, i am not able to figure it out.

I tried this -

for i in a:
    for j in i:
        j.replace("'"," ")
        for k,v in j:
            print(k,v)

But getting this

> ValueError: not enough values to unpack (expected 2, got 1)

Is there any way i can convert that weird json into normal json like below

[{"p": {"n":"s","i":"1"}},.....]

Any help will be appreciated, Thank you.

答案1

得分: 1

看起来你的字典的键和值是JSON字符串。你可以遍历它们并进行转换:

import json

a = [{'p': '{"n":"s","i":"1"}']

converted = [json.loads(k): json.loads(v) for k, v in d.items()} for d in a]
# [{'p': {'n': 's', 'i': '1'}}]

如果可能的话,最好检查一下是否可以从源数据中获得正确的数据,因为这似乎是数据源的问题。

英文:

It looks like the keys and value of your dictionaries are json strings. You could loop through and convert them:

import json

a =  [{'"p"': '{"n":"s","i":"1"}'}]

converted = [{json.loads(k): json.loads(v) for k, v in d.items()} for d in a]
# [{'p': {'n': 's', 'i': '1'}}]

If it's possible, it's worth checking to see it you can get proper data to start with because this seems like the source of the data is a problem.

答案2

得分: 1

你可以将键和值映射到json.loads,以将JSON格式的对象转换为Python对象:

[dict(map(json.loads, i) for i in d.items()) for d in a]

演示:https://replit.com/@blhsing/FlawedUtilizedPcboard

英文:

You can map the keys and values to json.loads to convert JSON-formatted objects to Python ones:

[dict(map(json.loads, i) for i in d.items()) for d in a]

Demo: https://replit.com/@blhsing/FlawedUtilizedPcboard

huangapple
  • 本文由 发表于 2023年3月7日 11:59:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75657926.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定