繁体   English   中英

使用FileReader读取JSON文件?

[英]Using FileReader to read a JSON file?

我正在尝试读取用户上传的JSON文件,然后尝试将其复制到数组中。 但是,使用.readAsText(),我得到的返回值具有字符串的格式(显然),例如包括\\“和\\ n以及其他类似字符串的属性。

有没有一种方法可以使用FileReader(或其他任何形式的不涉及服务器的读取文件)来读取JSON文件,并使其仅返回纯JSON?

例如,让它返回

[
  {"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));

它返回错误error TS2345: Argument of type 'FileReader' is not assignable to parameter of type 'string'

我可以将使用FileReader读取的内容转换为另一个字符串形式的变量,然后解析该新变量吗?

问题中的代码错误地使用了FileReader

FileReader .readAs<Type>操作是异步的。 FileReader具有loadloadend事件,其中event.targetFileReader实例的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); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM