如何让Bokeh生成格式化多行的docs_json而非单行?
解决Bokeh生成多行格式化JSON及批量处理方案
完全理解你的困扰!刚接触Bokeh遇到这种单行超大JSON的问题太正常了,尤其是要导入有行长度限制的WordPress,确实得换成格式化的多行版本。而且你还要批量处理数百个图表,我给你一套实用的解决方案:
一、单个图表生成格式化JSON
Bokeh本身生成的docs_json默认是压缩的单行格式,但我们可以借助Python的json模块轻松将其转换为带缩进的多行结构:
from bokeh.plotting import figure, curdoc import json # 1. 生成你的Bokeh图表 p = figure(title="示例图表") p.circle([1, 2, 3], [4, 5, 6]) # 2. 将图表添加到当前文档并获取原始JSON curdoc().add_root(p) raw_docs_json = curdoc().to_json() # 3. 格式化JSON为多行结构,indent指定缩进空格数(2或4都可以) formatted_json = json.dumps(raw_docs_json, indent=2, ensure_ascii=False) # 4. 保存或直接使用格式化后的JSON with open("formatted_chart.json", "w", encoding="utf-8") as f: f.write(formatted_json)
这样生成的JSON会自动换行并缩进,完美适配WordPress的行长度限制。
二、批量处理数百个图表
针对批量生成的场景,我们可以把图表生成和JSON格式化的逻辑封装成循环,自动化处理所有图表:
方案1:从数据源批量生成并格式化
如果你的图表是基于不同数据源批量生成的,可以用这样的脚本:
from bokeh.plotting import figure, curdoc import json import pandas as pd # 假设这里是你的批量数据源(比如从CSV/数据库读取的多个数据集) # 示例:用列表模拟数百个数据源 batch_data = [ {"x": [1,2,3], "y": [2,4,6], "title": "图表1"}, {"x": [1,3,5], "y": [1,9,25], "title": "图表2"}, # ... 更多数据源 ] for idx, data in enumerate(batch_data): # 清空当前文档,避免多个图表内容混淆 curdoc().clear() # 生成当前图表 p = figure(title=data["title"]) p.line(data["x"], data["y"]) curdoc().add_root(p) # 获取并格式化JSON raw_json = curdoc().to_json() formatted_json = json.dumps(raw_json, indent=2) # 保存为单独的文件,方便后续批量导入WordPress with open(f"chart_{idx+1}_formatted.json", "w") as f: f.write(formatted_json)
方案2:转换已有的单行JSON文件
如果已经有一批生成好的单行JSON文件,也可以批量转换:
import json import os # 指定存放单行JSON文件的文件夹 input_dir = "./single_line_charts" output_dir = "./formatted_charts" # 创建输出文件夹(如果不存在) os.makedirs(output_dir, exist_ok=True) # 遍历所有JSON文件 for filename in os.listdir(input_dir): if filename.endswith(".json"): input_path = os.path.join(input_dir, filename) output_path = os.path.join(output_dir, filename) # 读取单行JSON并格式化 with open(input_path, "r") as f: raw_json = json.load(f) formatted_json = json.dumps(raw_json, indent=2) with open(output_path, "w") as f: f.write(formatted_json)
三、关键注意事项
indent参数可以根据需求调整(比如设为4),只要生成的JSON是多行结构,就能避开WordPress的行长度限制。- 批量处理时,务必记得每次生成新图表前调用
curdoc().clear(),避免多个图表的JSON内容混杂。 - 如果你的图表是通过Bokeh Server动态生成的,同样可以在导出
docs_json时用上述方法格式化。
内容的提问来源于stack exchange,提问作者Teresa Anderson-Myers
相关产品推荐
相关产品推荐

