使用的FileReader读取JSON文件?

问题描述 投票:1回答:1

我想读一个JSON文件无我有,由用户上传,并尝试将其复制到一个数组。然而,随着.readAsText(),返回我得到了一个字符串(明显),如包括\”和\ n和其他弦属性的格式。

有没有一种方法,我可以使用的FileReader(或阅读文件的任何其他形式,不涉及服务器)来读取JSON文件,并将它返回只是普通的JSON?

例如,让它返回

[
  {"hello": "world"}
]

要么

[{"hello": "world"}]

并不是

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

?

编辑:我现在知道JSON.parse(文本)的方法,但解析的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读取另一个变种是一个字符串,然后解析新变种?

javascript typescript filereader
1个回答
5
投票

在这个问题的代码使用FileReader不正确。

FileReader .readAs<Type>操作是异步的。 FileReader具有loadloadend事件其中resultevent.target实例的FileReader属性是所得到的异步处理的数据。

不要解析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);
© www.soinside.com 2019 - 2024. All rights reserved.