forked from lokalise/i18n-ally
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjson.ts
51 lines (42 loc) · 1.29 KB
/
json.ts
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
import SortedStringify from 'json-stable-stringify'
// @ts-ignore
import JsonMap from 'json-source-map'
import { Parser } from './base'
export class JsonParser extends Parser {
id = 'json'
constructor() {
super(['json'], 'json')
}
async parse(text: string) {
if (!text || !text.trim())
return {}
return JSON.parse(text)
}
async dump(object: object, sort: boolean, compare: ((x: string, y: string) => number) | undefined) {
const indent = this.options.tab === '\t' ? this.options.tab : this.options.indent
if (sort)
return `${SortedStringify(object, { space: indent, cmp: compare ? (a, b) => compare(a.key, b.key) : undefined })}\n`
else
return `${JSON.stringify(object, null, indent)}\n`
}
annotationSupported = true
annotationLanguageIds = ['json']
parseAST(text: string) {
if (!text || !text.trim())
return []
const map = JsonMap.parse(text).pointers
const pairs = Object.entries<any>(map)
.filter(([k, v]) => k)
.map(([k, v]) => ({
quoted: true,
start: v.value.pos + 1,
end: v.valueEnd.pos - 1,
// https://tools.ietf.org/html/rfc6901
key: k.slice(1)
.replace(/\//g, '.')
.replace(/~0/g, '~')
.replace(/~1/g, '/'),
}))
return pairs
}
}