向数组添加元素后Pandas表格为空?代码问题排查求助
问题分析与修复:JSON数组添加条目后Pandas表格为空
我有一个内部包含多个数组的JSON对象,想向这些数组中添加条目。添加完成后将JSON数据转换为Pandas表格格式,却发现表格里所有条目都是空的。请帮忙检查下面的代码是否有问题?
import json import pandas as pd from IPython.display import HTML from datetime import datetime class A : t = '{"W":[],"X":[],"Y":[],"Z":[]}' def updatet(w,x,y,z): b = json.loads(A.t) b["W"].append(w) b["X"].append(x) b["Y"].append(y) b["Z"].append(z) df = pd.DataFrame(eval(A.t)) html = df.to_html() text_file = open("/tmp/index.html", "w") text_file.write(html) text_file.close() def addrecord(): A.updatet("A","B","C","D") A.updatet("E","F","G","H") a = A a.addrecord()
文件输出:
#cat /tmp/index.html <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>W</th> <th>X</th> <th>Y</th> <th>Z</th> </tr> </thead> <tbody> </tbody> </table>
问题根源
- 修改后的JSON未同步回类属性
在updatet方法中,你加载A.t得到字典b并添加了元素,但修改后的b没有重新序列化为JSON字符串赋值给A.t,导致类属性t始终是初始的空数组JSON。 - 错误使用
eval创建DataFrame
即便A.t被更新,eval在这里既不安全也无必要,直接用json.loads加载字典更稳妥。 - 类方法定义不规范
updatet作为类方法,未声明cls参数,会导致传入的参数错位,逻辑异常。
修复后的代码
import json import pandas as pd from datetime import datetime class A : t = '{"W":[],"X":[],"Y":[],"Z":[]}' @classmethod def updatet(cls, w, x, y, z): # 加载当前JSON为字典 b = json.loads(cls.t) # 添加元素到数组 b["W"].append(w) b["X"].append(x) b["Y"].append(y) b["Z"].append(z) # 将修改后的字典重新转为JSON,更新类属性 cls.t = json.dumps(b) # 用最新JSON创建DataFrame并生成HTML df = pd.DataFrame(json.loads(cls.t)) html = df.to_html() with open("/tmp/index.html", "w") as text_file: text_file.write(html) @classmethod def addrecord(cls): cls.updatet("A","B","C","D") cls.updatet("E","F","G","H") # 调用类方法 A.addrecord()
修复说明
- 用
@classmethod装饰器规范类方法,通过cls访问类属性 - 修改后的字典重新序列化为JSON字符串,同步更新类属性
t - 用
json.loads替代eval加载JSON数据,避免安全风险 - 使用
with语句管理文件,自动关闭文件,代码更安全规范
修复后生成的HTML表格会包含两行数据,不再为空。
内容的提问来源于stack exchange,提问作者Sandy
相关产品推荐
相关产品推荐

