Vim json_encode() and Vim json_decode()
let s = {'year' : 2023,
'animal' : ['dog', 'cat', 'cow', 'fox', 'rat']
}
" Encode text string to json object
let json = json_encode(s)
echo json
" ⟹ {"year": 2023, "animal": ["dog", "cat", "cow", "fox", "rat"]}
" Decode json object to text string
let jstr = json_decode(json)
echo jstr
" ⟹ {'year': 2023, 'animal': ['dog', 'cat', 'cow', 'fox', 'rat']}
" /tmp/x1.json contains the following json
{'year' : 2023,
'animal' : ['dog', 'cat', 'cow', 'fox', 'rat']
}
" join(readfile('/tmp/x1.json'), "\n") DOES NOT WORK ❌
" join(readfile('/tmp/x1.json'), '') DOES NOT WORK EITHER ❌
" join(readfile('/tmp/x1.json'), ' ') DOES WORK ✅, SPACE is important here.
let js = join(readfile('/tmp/x1.json', ' '))
" js is dictionary
echo js['year']
" ⟹ 2023
echo js['animal']
" ⟹ ['dog', 'cat', 'cow', 'fox', 'rat']