使用 FileReader 读取 JSON 文件?
Using FileReader to read a JSON file?
我正在尝试读取用户上传的 JSON 文件,并尝试将其复制到数组中。但是,使用 .readAsText(),我得到的 return 具有字符串格式(显然),例如包括 \" 和 \n 以及其他类似字符串的属性。
有没有一种方法可以使用 FileReader(或任何其他不涉及服务器的读取文件的形式)来读取 JSON 文件并使其 return 简单明了JSON?
例如,拥有它return
[
{"hello": "world"}
]
或
[{"hello": "world"}]
而不是
"[\n{\"hello\": \"world\"}\n]"
?
编辑:我现在知道 JSON.parse(text) 方法,但在解析 FileReader 对象时出现错误
let fileUploaded = new FileReader();
fileUploaded.readAsText(MY_JSON_FILE);
console.log(JSON.parse(fileUploaded));
它 return 是错误 error TS2345: Argument of type 'FileReader' is not assignable to parameter of type 'string'
我能否将使用 FileReader 读取的内容转换为另一个字符串变量,然后解析该新变量?
问题中的代码使用 FileReader
不正确。
FileReader
.readAs<Type>
操作是异步的。 FileReader
有 load
和 loadend
事件,其中 event.target
和 FileReader
实例的 result
属性 是结果异步处理的数据。
不解析 FileReader
对象本身。
.readAs<Type>
期望将 Blob
作为参数传递,而不是 JavaScript 普通对象。
const MY_JSON_FILE = [{
"hello": "world"
}];
let json = JSON.stringify(MY_JSON_FILE);
const blob = new Blob([json], {type:"application/json"});
const fr = new FileReader();
fr.addEventListener("load", e => {
console.log(e.target.result, JSON.parse(fr.result))
});
fr.readAsText(blob);
我正在尝试读取用户上传的 JSON 文件,并尝试将其复制到数组中。但是,使用 .readAsText(),我得到的 return 具有字符串格式(显然),例如包括 \" 和 \n 以及其他类似字符串的属性。
有没有一种方法可以使用 FileReader(或任何其他不涉及服务器的读取文件的形式)来读取 JSON 文件并使其 return 简单明了JSON?
例如,拥有它return
[
{"hello": "world"}
]
或
[{"hello": "world"}]
而不是
"[\n{\"hello\": \"world\"}\n]"
?
编辑:我现在知道 JSON.parse(text) 方法,但在解析 FileReader 对象时出现错误
let fileUploaded = new FileReader();
fileUploaded.readAsText(MY_JSON_FILE);
console.log(JSON.parse(fileUploaded));
它 return 是错误 error TS2345: Argument of type 'FileReader' is not assignable to parameter of type 'string'
我能否将使用 FileReader 读取的内容转换为另一个字符串变量,然后解析该新变量?
问题中的代码使用 FileReader
不正确。
FileReader
.readAs<Type>
操作是异步的。 FileReader
有 load
和 loadend
事件,其中 event.target
和 FileReader
实例的 result
属性 是结果异步处理的数据。
不解析 FileReader
对象本身。
.readAs<Type>
期望将 Blob
作为参数传递,而不是 JavaScript 普通对象。
const MY_JSON_FILE = [{
"hello": "world"
}];
let json = JSON.stringify(MY_JSON_FILE);
const blob = new Blob([json], {type:"application/json"});
const fr = new FileReader();
fr.addEventListener("load", e => {
console.log(e.target.result, JSON.parse(fr.result))
});
fr.readAsText(blob);