How to read JSON file with React-Native-fs

后端 未结 2 813
情话喂你
情话喂你 2021-01-27 10:35

I have a asset.json file with content, and need to read it within an react-native app. I already figured that it must be manually copied to the native implementation and I can v

相关标签:
2条回答
  • 2021-01-27 11:00

    Steps to read json file in react-native applications :-

    1. Import it in your component

    import ASSET_FILE from '../assets/files/asset.json';
    

    // import filename from 'path to your asset file';

    2. Now in a funtion

    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.
    

    Iterate if or save in state if you want to show in your application..

    Hope this helps...Thanks :)

    0 讨论(0)
  • 2021-01-27 11:16

    I managed finally to copy the content of the static file into the application document directory and read and maintain it there by using NRFechtBlob.fs implementation with provided encoding param like this:

    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);
    

    puh. didn't thought that file handling could be such a pain in 2019.

    0 讨论(0)
提交回复
热议问题