Как читать файл JSON с помощью React-Native-fs
У меня есть файл asset.json с содержимым, и мне нужно прочитать его в приложении, поддерживающем реакцию. Я уже подумал, что его нужно вручную скопировать в нативную реализацию, и я могу убедиться, что файл там (и доступен для чтения: -rw-r-r--). Поскольку он там, и я использую обещания для его получения, скажите, пожалуйста, какой результат остался:
{"_40":0,"_65":0,"_55":null,"_72":null}
а не содержимое файла.
const path = RNFetchBlob.fs.dirs.DocumentDir + '/' + ASSET_FILENAME;
if (await RNFS.exists(path)){
console.log("BLAH EXISTS");
} else {
console.log("BLAH DOES NOT EXIST");
}
const asset_content = await RNFS.readFile(path);
console.log("local asset_content:", asset_content);
const assets = JSON.parse(asset_content);
console.log("local assets:", assets);
Результат:
[10:03:55] I | ReactNativeJS ▶︎ BLAH EXISTS
[10:03:55] I | ReactNativeJS ▶︎ 'local asset_content:', '{"_40":0,"_65":0,"_55":null,"_72":null}'
[10:03:55] I | ReactNativeJS ▶︎ 'local assets:', { _40: 0, _65: 0, _55: null, _72: null }
если я с другой стороны использую promisify
по какой-либо причине, как предлагается в некоторых сообщениях, приложение зависает при вызове чтения обещанного файла. Вот код с внесенными изменениями:
const path = RNFetchBlob.fs.dirs.DocumentDir + '/' + ASSET_FILENAME;
if (await RNFS.exists(path)){
console.log("BLAH EXISTS");
} else {
console.log("BLAH DOES NOT EXIST");
}
const readFileAsync = promisify(RNFS.readFile);
const asset_content = await readFileAsync(path);
console.log("local asset_content:", asset_content);
const assets = JSON.parse(asset_content);
console.log("local assets:", assets);
И его вывод:
[10:24:16] I | ReactNativeJS ▶︎ BLAH EXISTS
Файл небольшой, всего 81 строка действительного JSON. Теперь, если я использую обещание, чтобы проверить какое-либо исключение, подобное этому:
const path = RNFetchBlob.fs.dirs.DocumentDir + '/' + ASSET_FILENAME;
if (await RNFS.exists(path)){
console.log("BLAH EXISTS");
} else {
console.log("BLAH DOES NOT EXIST");
}
const readFileAsync = promisify(RNFS.readFile);
let asset_content = null;
readFileAsync(path, 'utf8')
.then((str) => {
console.log("got result: ", str);
asset_content = str;
})
.catch((e) => {
console.log("got error:", e);
});
console.log("local asset_content:", asset_content);
const assets = JSON.parse(asset_content);
console.log("local assets:", assets);
У меня по-прежнему нет исключения, и результат нулевой:
[10:45:00] I | ReactNativeJS ▶︎ BLAH EXISTS
[10:45:00] I | ReactNativeJS ▶︎ 'local asset_content:', null
[10:45:00] I | ReactNativeJS ▶︎ 'local assets:', null
и когда я избавляюсь от promisify и оставляю обработку обещаний, я возвращаюсь туда, откуда начал:
const path = RNFetchBlob.fs.dirs.DocumentDir + '/' + ASSET_FILENAME;
if (await RNFS.exists(path)){
console.log("BLAH EXISTS");
} else {
console.log("BLAH DOES NOT EXIST");
}
let asset_content = null;
RNFS.readFile(path, 'utf8')
.then((str) => {
console.log("got result: ", str);
asset_content = str;
})
.catch((e) => {
console.log("got error:", e);
});
console.log("local asset_content:", asset_content);
const assets = JSON.parse(asset_content);
console.log("local assets:", assets);
выход:
[10:49:45] I | ReactNativeJS ▶︎ BLAH EXISTS
[10:49:45] I | ReactNativeJS ▶︎ 'local asset_content:', null
[10:49:45] I | ReactNativeJS ▶︎ 'local assets:', null
[10:49:45] I | ReactNativeJS ▶︎ 'got result: ', '{"_40":0,"_65":0,"_55":null,"_72":null}'
Пожалуйста помоги. Обработка файлов имеет решающее значение для нашего приложения.
ОБНОВЛЕНИЕ: вот содержимое файла asset.json, на который ссылается ASSET_FILE:
{
"protobuf": [
{
"name": "tiny-fovapp-4c",
"lite": false,
"compressed": false,
"selected": false
},
{
"name": "tiny-yolo-4c-quantized",
"lite": true,
"compressed": true,
"selected": false
},
{
"name": "tiny-yolo-4c",
"parentFolder": "/data/user/0/com.foviar/files/",
"modelFilePath": "ai/protobuf/tiny-yolo-4c.pb",
"labelsFilePath": "ai/protobuf/tiny-yolo-4c-labels.txt",
"lite": false,
"compressed": false,
"selected": true
},
{
"name": "tiny-yolo-4c",
"lite": true,
"compressed": false,
"selected": false
}
],
"testImages": [
{
"name": "IMG_6924.jpg",
"parentFolder": "/data/user/0/com.foviar/files/",
"filePath": "ai/testimgs/IMG_6924.jpg"
},
{
"name": "IMG_6924.png",
"parentFolder": "/data/user/0/com.foviar/files/",
"filePath": "ai/testimgs/IMG_6924.png"
},
{
"name": "IMG_6929.jpg",
"parentFolder": "/data/user/0/com.foviar/files/",
"filePath": "ai/testimgs/IMG_6929.jpg"
},
{
"name": "Part1.png",
"parentFolder": "/data/user/0/com.foviar/files/",
"filePath": "ai/testimgs/Part1.png"
},
{
"name": "Part1_10.png",
"parentFolder": "/data/user/0/com.foviar/files/",
"filePath": "ai/testimgs/Part1_10.png"
}
],
"parts": [
{
"name": "Part1",
"parentFolder": "/data/user/0/com.foviar/files/",
"modelFilename": "ai/models/Part1.png",
"drawingFilename": "ai/drawings/Part1.png",
"annotationFilename": "ai/annotations/Part1.xml"
},
{
"name": "Part2",
"parentFolder": "/data/user/0/com.foviar/files/",
"modelFilename": "ai/models/Part2.png",
"drawingFilename": "ai/drawings/Part2.png",
"annotationFilename": "ai/annotations/Part2.xml"
},
{
"name": "Part3",
"parentFolder": "/data/user/0/com.foviar/files/",
"modelFilename": "ai/models/Part3.png",
"drawingFilename": "ai/drawings/Part3.png",
"annotationFilename": "ai/annotations/Part3.xml"
}
]
}
2 ответа
Мне, наконец, удалось скопировать содержимое статического файла в каталог документов приложения, прочитать и сохранить его там, используя реализацию NRFechtBlob.fs с предоставленным параметром кодирования, например:
let asset_content = null;
try {
await RNFetchBlob.fs.readFile(assetFile_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);
пух. не думал, что обработка файлов может быть такой головной болью в 2019 году.
Шаги по чтению файла json в приложениях, поддерживающих реакцию: -
1. Импортируйте его в свой компонент
import ASSET_FILE from '../assets/files/asset.json';
// импортировать имя файла из 'пути к файлу вашего ресурса';
2. Теперь в функции
jsonParser(){
var data = JSON.parse(JSON.stringify(ASSET_FILE));
var tempProtobuf = []
var temptestImages= []
var tempparts= []
tempProtobuf = data.Protobuf
temptestImages = data.testImages
tempparts = data.parts
}
// Now three of your objects are there in tempProtobuf, temptestImages, tempparts array respectively.
Выполните итерацию, если или сохраните в состоянии, если вы хотите показать в своем приложении.
Надеюсь, это поможет... Спасибо:)