I want to parse array in typescript.
My code is below:
interface MyObj {
val1: string
val2: string
val3: string
}
const fs = require('fs')
const file = 'test.json'
const encode = 'utf8'
const jsonString = '[{val1 : "test1", val2 : "test2", val3 : "test3"}, { val1 : "test4", val2 : "test5", val3 : "test3"}]'
fs.writeFile(file, JSON.stringify(jsonString))
fs.readFile(file, encode, (err, data) => {
const objs = JSON.parse(data) as MyObj[]
console.log(data)
console.log(objs)
for (const obj of objs) {
console.log(obj)
console.log(obj.val1)
console.log(obj.val2)
console.log(obj.val3)
}
})
Then the result is the following:
"[{val1 : \"test1\", val2 : \"test2\", val3 : \"test3\"}, { val1 : \"test4\", val2 : \"test5\", val3 : \"test6\"}]"
[{val1 : "test1", val2 : "test2", val3 : "test3"}, { val1 : "test4", val2 : "test5", val3 : "test6"}]
[
undefined
undefined
undefined
{
undefined
undefined
undefined
v
undefined
undefined
undefined
a
undefined
undefined
undefined
l
undefined
undefined
undefined
1
undefined
undefined
undefined
.
.
.
Seems parse is successful but maybe there are some wrong syntax after parsing but cannot find them.
My environment is :
MacOS 10.12.6
NPM 5.6.0
TypeScript 2.9.1
I appreciate any helps.