const { Plugin } = require('obsidian');
class JsonMdTableConverterPlugin extends Plugin {
async onload() {
// 注册指令
this.addCommand({
id: 'convert-json-md-table',
name: 'JSON/MD Table Converter',
callback: () => {
this.convertToJsonOrMd();
},
});
// 注册右键菜单
this.registerEvent(
this.app.workspace.on('editor-menu', (menu, editor, event) => {
menu.addItem((item) => {
item
.setTitle('JSON/MD Table Converter')
.setIcon('dice')
.onClick(() => {
this.convertToJsonOrMd();
});
});
})
);
}
convertToJsonOrMd() {
const activeLeaf = this.app.workspace.activeLeaf;
if (!activeLeaf) return;
const editor = activeLeaf.view.sourceMode.cmEditor;
const text = editor.getSelection() || editor.getValue();
let result = '';
try {
// 尝试将文本解析为JSON
const json = JSON.parse(text);
if (
Array.isArray(json) &&
json.length > 0 &&
typeof json[0] === 'object'
) {
// 转换为Markdown表格
result = this.jsonToMdTable(json);
} else {
// 如果不是数组或者数组元素不是对象,则提示用户
return new Notice('Invalid JSON: JSON must be an array of objects.');
}
} catch (e) {
const msg = this.isMarkdownTable(text);
if (msg !== 'success') {
return new Notice(msg);
}
// 解析失败,可能是Markdown表格
result = JSON.stringify(this.mdTableToJson(text), null, 2);
}
editor.replaceSelection(result);
}
jsonToMdTable(json) {
const fieldSet = new Set(); // 使用Set来存储不重复的字段
for (let i = 0; i < json.length; i++) {
const elementKeys = Object.keys(json[i]);
for (let j = 0; j < elementKeys.length; j++) {
fieldSet.add(elementKeys[j]); // 将字段添加到Set中
}
}
const headers = Array.from(fieldSet);
const headerRow = '| ' + headers.join(' | ') + ' |';
const separatorRow = '| ' + headers.map(() => ':--:').join(' | ') + ' |';
const bodyRows = json.map(
(obj) =>
'| ' + headers.map((header) => obj[header] || '').join(' | ') + ' |'
);
return [headerRow, separatorRow, ...bodyRows].join('\n');
}
mdTableToJson(mdTable) {
const rows = mdTable.split('\n').filter((row) => row.trim() !== '');
for (let i = 0; i < rows.length; i++) {
rows[i] = rows[i].replace(/^\|+|\|+$/g, '');
}
const headers = rows[0].split('|').map((header) => header.trim());
const jsonArray = rows.slice(2).map((row) => {
const values = row.split('|').map((value) => value.trim());
return headers.reduce((obj, header, index) => {
obj[header] = values[index];
return obj;
}, {});
});
return jsonArray;
}
isMarkdownTable(str) {
// 去除字符串首尾的空白字符,并按行分割
const lines = str.trim().split('\n');
const msg =
'Conversion failed: The selected text is neither valid JSON nor a Markdown table.';
// 检查至少有两行
if (lines.length < 2) {
return msg;
}
// 检查每行是否至少包含一个'|'
for (let line of lines) {
if (line.indexOf('|') === -1) {
return msg;
}
}
let separatorLine = lines[1].replaceAll(' ', '');
// 分隔符行应该由'-'或':'组成,并且由'|'分隔
if (separatorLine.startsWith('|')) { // 只去掉首尾的各一个'|'
separatorLine = separatorLine.slice(1);
}
if (separatorLine.endsWith('|')) {
separatorLine = separatorLine.slice(0, -1);
}
const separators = separatorLine.split('|');
for (let separator of separators) {
separator = separator.replaceAll(' ', '');
if (separator.startsWith(':')) {
separator = separator.slice(1);
}
if (separator.endsWith(':')) {
separator = separator.slice(0, -1);
}
if (!/^-+$/.test(separator)) {
return msg;
}
}
// 检查分隔符行与标题行和内容行的列数是否匹配
for (let line of lines) {
line = line.trim()
if (line.startsWith('|')) {
line = line.slice(1);
}
if (line.endsWith('|')) {
line = line.slice(0, -1);
}
const pipeCount = line.split('|').length;
if (pipeCount !== separators.length) {
return msg;
}
}
if (lines.length == 2) {
return 'Conversion failed: Markdown table should contain at least one row of data.';
}
return 'success';
}
}
module.exports = JsonMdTableConverterPlugin;
没有合适的资源?快使用搜索试试~ 我知道了~
工具轻松转换JSON与Markdown表格-自制Obsidian插件
![preview](https://csdnimg.cn/release/downloadcmsfe/public/img/white-bg.ca8570fa.png)
共2个文件
json:1个
js:1个
![preview-icon](https://csdnimg.cn/release/downloadcmsfe/public/img/scale.ab9e0183.png)
0 下载量 167 浏览量
2024-07-23
15:22:15
上传
评论
收藏 2KB ZIP 举报
温馨提示
轻松转换JSON与Markdown表格——自制Obsidian插件
资源推荐
资源详情
资源评论
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![zip](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![jar](https://img-home.csdnimg.cn/images/20210720083455.png)
![zip](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![jar](https://img-home.csdnimg.cn/images/20210720083455.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
收起资源包目录
![package](https://csdnimg.cn/release/downloadcmsfe/public/img/package.f3fc750b.png)
![file-type](https://csdnimg.cn/release/download/static_files/pc/images/minetype/UNKNOWN.png)
![file-type](https://csdnimg.cn/release/download/static_files/pc/images/minetype/UNKNOWN.png)
共 2 条
- 1
资源评论
![avatar-default](https://csdnimg.cn/release/downloadcmsfe/public/img/lazyLogo2.1882d7f4.png)
![avatar](https://profile-avatar.csdnimg.cn/af15b333c9c54eddad9b82b63110cccb_qq_40205510.jpg!1)
RumIV
- 粉丝: 687
- 资源: 28
上传资源 快速赚钱
我的内容管理 展开
我的资源 快来上传第一个资源
我的收益
登录查看自己的收益我的积分 登录查看自己的积分
我的C币 登录后查看C币余额
我的收藏
我的下载
下载帮助
![voice](https://csdnimg.cn/release/downloadcmsfe/public/img/voice.245cc511.png)
![center-task](https://csdnimg.cn/release/downloadcmsfe/public/img/center-task.c2eda91a.png)
最新资源
- C、C++项目开发资源.docx
- SolidWorksAddinStudy-solidworks
- termux-install-linux-kali linux安装教程
- macos-virtualbox-虚拟机安装linux
- lanproxy-tcp/ip协议
- IntegerProgExperiment-线性规划
- numpy_calculation_question_set-jupyter notebook安装
- IESOptimization-gurobi
- Machine-Learning-Navigation-模拟退火算法matlab代码
- LeetCode从简单到困难-每日一题-动态规划法求解0-1背包
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈
![feedback](https://img-home.csdnimg.cn/images/20220527035711.png)
![feedback](https://img-home.csdnimg.cn/images/20220527035711.png)
![feedback-tip](https://img-home.csdnimg.cn/images/20220527035111.png)
安全验证
文档复制为VIP权益,开通VIP直接复制
![dialog-icon](https://csdnimg.cn/release/downloadcmsfe/public/img/green-success.6a4acb44.png)