python - 从python中的json文件中提取元素
问题描述
使用 Python,我有以下 JSON 结构:
[
{
"id": 1,
"data": "{'id': '1', 'title': 'title of id 1', 'foo': 'bar', 'fooo': ['bar', 'baar']}"
},
{
"id": 2,
"data": "{'id': '2', 'title': 'title of id 2', 'foo': 'bar', 'fooo': ['bar', 'baar']}"
},
{
"id": 3,
"data": "{'id': '3', 'title': 'title of id 3', 'foo': 'bar', 'fooo': ['bar', 'baar']}"
}
]
我想将第一个数据元素存储在一个新的 .json 中,例如
[
{
1 : 'title of 1',
2 : 'title of 2',
...
}
]
现在,我尝试了很多东西,最近的是:
Index = []
for x in checklists:
item = {"id": x}
Index.append(x)
return Index
或者
Index = []
for x in checklists:
x = json.dumps(x)
Index.append(x.id)
return Index
但是每次我尝试执行它时,我都会收到相同的错误:
AttributeError: 'str' object has no attribute 'id'
这引出了我的问题。我的 json 格式是否错误?还是我的功能错了?
解决方案
没有 ast 需要一些工作才能完成这项工作。问题是数据块是一个字符串(这是有效的 json),但不是你想要的。
您想要的是要格式化的数据中的数据 comme ca:
{
"id": 1,
"data": {"id": "1", "title": "title of id 1", "foo": "bar"}
}
现在,当您遍历每个数据块(其中 json_array 是您的完整 json)时:
for json_block in json_array:
temp = json_block['data']
title = (temp['title'])
或者:
for json_block in json_array:
title= json_block['data']['title']
您现在可以轻松地将每个标题添加到新数组中:
index_list.append({'id': title})
整个方法看起来像:
def create_new_json():
index_list = []
for json_block in json_array:
index_list.append({json_block ['id']: json_block ['data']['title']})
推荐阅读
- java - 平移 BufferedImage
- php - 如何发送字符串数组 Guzzle
- java - Java字符串用评估的键替换正则表达式模式
- rust - 为什么在使用期货箱中的 block_on 时,我会“对‘当前未在 Tokio 运行时运行’感到恐慌”?
- ruby-on-rails - 警告:以 \r 结尾的 shebang 行可能会导致问题。导轨中止
- javascript - 从 scriptJS 加载 html
- node.js - react-images-uploader:以反应形式获取上传图像的文件名或网址
- java - 使用 JUnit 和 Mockito 测试内部类的重写方法
- c# - 为什么 .NET Core Worker Service 在 ExecuteAsync 方法中有两种不同的异常行为?
- python - 如何从大型python数据框中的复杂字符串中提取数字