在React Native上使用RNFS读取Json文件 [英] Reading Json file with RNFS on react native
本文介绍了在React Native上使用RNFS读取Json文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试访问我刚刚用RNFS编写的JSON文件的内容. 我尝试了不同的方法,例如导入,json-loader等,但均未成功.
I'am trying to access the content of a JSON file i just wrote with RNFS. I tried different ways, import, json-loader etc without success.
我这样写文件:
var obj = {
date: moment().format(),
counter: 0 };
var json = JSON.stringify(obj);
RNFS.writeFile(path, json, 'utf8')
.then((success) => {
count++;
console.log('FILE WRITTEN! : ');
})
.catch((err) => {
console.log(err.message);
});
然后我继续尝试阅读
var path = RNFS.DocumentDirectoryPath + '/test.json';
const cFile = RNFS.readFile(path, 'utf8');
可悲的是,我只能得到一个承诺",但似乎无法直接访问数据. 我在控制台中得到了这种结果.
Sadly i only get a 'promise' but can't seem to access directly the data. I get this kind of result in console.
Promise {_40: 0, _65: 0, _55: null, _72: null}
_40:0
_55:"{"date":"2018-04-11T10:52:52+02:00","counter":0}"
_65:1
_72:null
__proto__:Object
我想访问日期字段,就像cFile.date
And i would like to access the date field, just like cFile.date
任何帮助都欢迎您
推荐答案
尝试一下:
let asset_content = null;
try {
await RNFetchBlob.fs.readFile(path, 'utf8')
.then((data) => {
asset_content = data;
console.log("got data: ", data);
})
.catch((e) => {
console.error("got error: ", e);
})
} catch (err) {
console.log('ERROR:', err);
}
const assets = JSON.parse(asset_content);
这篇关于在React Native上使用RNFS读取Json文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文