业务需求:前端自己获取项目下的YAML,并且对YAML与JSON进行相互转换
1.实现效果如下:
2.具体实现
- 将yaml文件放到public文件夹下的yaml文件夹下
- 需要借助 js-yaml 来对yaml和json相互转换,load是yaml转换成json的API,dump是json转换成yaml的API
- 主要代码如下:
import yaml from 'js-yaml
// 读取Yaml
readFile() {
const file = this.loadFile('/yaml/test.yaml')
console.info('file--------------', file)
const json = yaml.load(file) // YAML输出为 json 格式
console.log('yaml转换json',json)
this.editor.csiJson = JSON.stringify(json, null, 2) //实现将文件内容展示到编辑器中
console.info('json转换yaml', yaml.dump(JSON.parse(this.editor.csiJson)) )
},
// 读取文件
loadFile(name) {
const xhr = new XMLHttpRequest()
const okStatus = document.location.protocol === 'file:' ? 0 : 200
xhr.open('GET', name, false)
xhr.overrideMimeType('text/html;charset=utf-8') // 默认为utf-8
xhr.send(null)
return xhr.status === okStatus ? xhr.responseText : null
},