我正在尝试使用 JMESPath 的 Python 库从大型 JSON 文件中提取信息,这里有一个简单得多的示例:
{
"high_name":"test",
"sections":[
{
"name":"section1",
"item":"string1"
},
{
"name":"section2",
"item":"string2",
"items_sub":[
{
"item":"deeper string1"
}
]
}
]
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试获得这样的输出:
{
"high_name":"test",
"sections":[
{
"name":"section1",
"items":[
"string1"
]
},
{
"name":"section2",
"items":[
"string1",
"deeper string1"
]
}
]
}
Run Code Online (Sandbox Code Playgroud)
更深的字符串可以是 1 到 3 层深,具体取决于部分的类型。我需要搜索键来获取所有匹配的item名称。
我已经使用 jsonpath-rw-ext 成功完成了此操作,但想知道是否可以使用 JMESPath 来消除对两个库的依赖?
我似乎无法找到一种方法来搜索所有子键,无论它们在 JMESPath 中的级别如何。
JSONPATH-RW-EXT 的工作字符串:
$.sections[*]..item
Run Code Online (Sandbox Code Playgroud)
使用 JMESPath 的最佳尝试(不起作用):
sections[*].*.item
Run Code Online (Sandbox Code Playgroud) 我返回了一些 JSON 数据,如下所示:(我无法更改结构)
[
{
"id": "d6aca8ac",
"owner": "test",
"sections": {
"summary": {
"id": "d417cd0e",
"notes": "",
"created_at": "2018-11-26T19:02:06Z"
},
"weather": {
"id": "7ef34660",
"notes": ""
},
"task": {
"id": "255d86dc",
"tasks": [
{
"id": "t1",
"total_hours": 176.0,
"updated_at": "2018-11-26T19:02:06Z",
"created_at": "2018-11-26T19:02:06Z"
},
{
"id": "t2",
"total_hours": 176.0,
"updated_at": "2018-11-26T19:02:06Z",
"created_at": "2018-11-26T19:02:06Z"
}
]
}
}
}
]
Run Code Online (Sandbox Code Playgroud)
我正在尝试使用 pandas 中的 json_normalise 将任务放入数据框中,如下所示:
+----+-------------+----------------------+----------------------+
| id | total_hours | updated_at | created_at |
+----+-------------+----------------------+----------------------+
| t1 | 176 | 2018-11-26T19:02:06Z …Run Code Online (Sandbox Code Playgroud) 我通过 .json() 函数中内置的请求创建了一个 Python 中的 JSON 对象。
这是我正在做的事情的简化示例:
data = session.get(url)
obj = data.json()
s3object = s3.Object(s3_bucket, output_file)
s3object.put(Body=(bytes(json.dumps(obj).encode('UTF-8'))))
Run Code Online (Sandbox Code Playgroud)
示例对象:
{'id': 'fab779b7-2586-4895-9f3b-c9518f34e028', 'project_id': 'a1a73e68-9943-4584-9d59-cc84a0d3e92b', 'created_at': '2017-10-23 02:57:03 -0700', 'sections': [{'section_name': '', 'items': [{'id': 'ffadc652-dd36-4b9f-817c-6539a4b462ab', 'created_at': '2017-10-23 03:36:13 -0700', 'updated_at': '2017-10-23 03:38:32 -0700', 'created_by': 'paul', 'question_text': 'Drawing Ref(s)', 'spec_ref': '', 'display_number': null, 'response': '', 'comment': 'see attached mh309', 'position': 1, 'is_conforming': 'N/A', 'display_type': 'text'}]}]}
Run Code Online (Sandbox Code Playgroud)
在将 JSON 上传到 S3 之前,无论其键或位置如何,我都需要将出现的任何字符串“N/A”替换为“Not Applicable”。我无法使用本地磁盘写入,因此这是这样做的原因。
这可能吗?
我原来的计划是把它变成一根弦,然后替换掉再返回,这样效率低吗?
谢谢,