简体   繁体   English

使用FileReader读取JSON文件?

[英]Using FileReader to read a JSON file?

I'm trying to read a JSON file I have, uploaded by the user, and try to copy it to an array. 我正在尝试读取用户上传的JSON文件,然后尝试将其复制到数组中。 However, with a .readAsText(), the return I get has the formatting of a string (obviously), such as including \\" and \\n and other string-like properties. 但是,使用.readAsText(),我得到的返回值具有字符串的格式(显然),例如包括\\“和\\ n以及其他类似字符串的属性。

Is there a way I can use FileReader (or any other form of reading files, that don't involve a server) to read the JSON file and have it return just the plain JSON? 有没有一种方法可以使用FileReader(或其他任何形式的不涉及服务器的读取文件)来读取JSON文件,并使其仅返回纯JSON?

For example, having it return 例如,让它返回

[
  {"hello": "world"}
]

or 要么

[{"hello": "world"}]

and not 并不是

"[\n{\"hello\": \"world\"}\n]"

?

Edit: I am now aware of the JSON.parse(text) method, but I'm getting an error when parsing the FileReader object 编辑:我现在知道JSON.parse(text)方法,但是在解析FileReader对象时出现错误

 let fileUploaded = new FileReader();
 fileUploaded.readAsText(MY_JSON_FILE);
 console.log(JSON.parse(fileUploaded));

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

Can I get what i read with FileReader to another var that is a string, and then parse that new var? 我可以将使用FileReader读取的内容转换为另一个字符串形式的变量,然后解析该新变量吗?

The code at the question uses FileReader incorrectly. 问题中的代码错误地使用了FileReader

FileReader .readAs<Type> operation is asynchronous. FileReader .readAs<Type>操作是异步的。 FileReader has load and loadend events where the result property of event.target and FileReader instance is the resulting asynchronously processed data. FileReader具有loadloadend事件,其中event.targetFileReader实例的result属性是生成的异步处理数据。

Do not parse the FileReader object itself. 不要解析FileReader对象本身。

.readAs<Type> expects a Blob to be passed as parameter, not a JavaScript plain object. .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