You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

解析嵌套JSON获取statement值时遇语法错误求助

问题解决方案

1. 修复语法错误

报错SyntaxError: invalid character '‘' (U+2018)的原因是代码中使用了中文单引号(‘’),Python仅支持英文单引号('')或双引号("")。将代码里的中文引号替换为英文即可:

import cx_Oracle
import json
import pandas as pd
f = open('test.json')
records = json.load(f)
pd.json_normalize(records, record_path = ['ddl'], meta =['op_type', 'op_ts','pos','xid'])

2. 提取statement字段的值

如果你的核心需求是获取statement的值,可通过以下两种方式实现:

方式一:借助pandas展开后提取

修改后的代码运行后会生成展开的DataFrame,直接提取statement列即可:

import json
import pandas as pd

# 读取JSON文件
with open('test.json', 'r') as f:
    records = json.load(f)

# 展开嵌套JSON结构
df = pd.json_normalize(records, record_path=['ddl'], meta=['op_type', 'op_ts','pos','xid'])
# 获取第一条记录的statement值
statement = df['statement'].iloc[0]
print(statement)  # 输出: create table srctab2

方式二:直接遍历JSON对象提取

无需依赖pandas,直接操作JSON数据更轻量化:

import json

with open('test.json', 'r') as f:
    records = json.load(f)

# 遍历每条记录提取statement
for item in records:
    statement = item['ddl']['statement']
    print(statement)  # 输出: create table srctab2

内容的提问来源于stack exchange,提问作者Subhash Tiwari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 01:01:51