英文:
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]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论