/
json-to-yaml.js
53 lines (42 loc) · 1.18 KB
/
json-to-yaml.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import YAML from "js-yaml"
export default function(editor) {
editor.on("paste", e => {
const originalStr = e.text
if (!isJSON(originalStr)) {
return
}
let yamlString
try {
yamlString = YAML.dump(YAML.load(originalStr), {
lineWidth: -1 // don't generate line folds
})
} catch (e) {
return
}
if (!confirm("Would you like to convert your JSON into YAML?")) {
return
}
// using SelectionRange instead of CursorPosition, because:
// SR.start|end === CP when there's no selection
// and it catches indentation edge cases when there is one
const padding = makePadding(editor.getSelectionRange().start.column)
// update the pasted content
e.text = yamlString
.split("\n")
.map((line, i) => i == 0 ? line : padding + line) // don't pad first line, it's already indented
.join("\n")
.replace(/\t/g, " ") // tabs -> spaces, just to be sure
})
}
function isJSON (str){
// basic test: "does this look like JSON?"
let regex = /^[ \r\n\t]*[{\[]/
return regex.test(str)
}
function makePadding(len) {
let str = ""
while(str.length < len) {
str += " "
}
return str
}