如何将多文档YAML解析转换为JS对象/JSON数组?
将多文档YAML转为普通JS对象数组(yaml库解决方案)
你可以通过两种方式实现需求:
方法1:转换已得到的Document数组
如果已经通过parseAllDocuments拿到了Document类型的数组,只需调用每个Document实例的toJSON()方法,就能得到纯数据的普通JS对象:
import yaml from 'yaml'; // 你的多文档YAML内容 const yamlContent = `--- message: Object has changed to concrete class. date: 2022-11-30T07:33:07.992955008Z reponame: myRepo --- message: Type has been created. date: 2022-11-30T07:33:07.992956372Z reponame: myRepo --- message: Constant has been created. date: 2022-11-30T07:33:07.992956372Z reponame: myRepo`; // 解析为Document数组 const docs = yaml.parseAllDocuments(yamlContent); // 转换为普通对象数组 const objArray = docs.map(doc => doc.toJSON()); // 如需转为JSON字符串 const jsonStr = JSON.stringify(objArray); console.log(jsonStr);
方法2:直接解析为普通对象数组
yaml库提供了parseAll方法,无需处理Document实例,直接返回原生JS对象数组,更贴合你的需求:
import yaml from 'yaml'; const yamlContent = `--- message: Object has changed to concrete class. date: 2022-11-30T07:33:07.992955008Z reponame: myRepo --- message: Type has been created. date: 2022-11-30T07:33:07.992956372Z reponame: myRepo --- message: Constant has been created. date: 2022-11-30T07:33:07.992956372Z reponame: myRepo`; // 直接得到普通对象数组 const objArray = yaml.parseAll(yamlContent); console.log(objArray);
补充说明
parseAllDocuments返回的Document实例包含YAML文档的元数据(比如注释、位置信息),而parseAll会自动忽略这些元数据,直接输出纯业务数据的对象数组。如果只需要数据内容,优先使用parseAll方法更高效。
内容的提问来源于stack exchange,提问作者AlexUA
相关产品推荐
相关产品推荐

