How to Read Json File in React Native

Fetching JSON (JavaScript Object Note) data in React Native from Local (E.g. IOS/Android storage) is different from fetching JSON information from a server (using Fetch or Axios). It requires Storage permission for APP and a Library to provide Native filesystem access.

Implementation: At present let'southward start with the implementation:

  • Step 1: Open up your terminal and install expo-cli by the following command.

    npm install -g expo-cli
  • Stride 2: At present create a project by the following command.

    expo init jsonDemo
  • Step 3: Now become into your project folder i.e. jsonDemo

    cd jsonDemo

Project Structure: It will look like the following.

Directory Structure

Instance: Fetching data from a local JSON file in React Native.

Step 1: Install react-native-fs using the following control:

npm install react-native-fs

Note: If you are getting errors like Effort to go length of null array EUNSPECIFIED and then in the android manifest file add the following code.

XML

< manifest ...>

< uses-permission android:proper noun = "android.permission.READ_EXTERNAL_STORAGE" />

< uses-permission android:name = "android.permission.WRITE_EXTERNAL_STORAGE" />

< awarding

android:requestLegacyExternalStorage = "true"

...>

...

</ application >

</ manifest >

Footstep 2: Create a JSON file named information.json and identify it in android's "/storage/emulated/0/" directory which is default ExternalStorageDirectoryPath of android. You can too change the location of the JSON file simply make sure to shop its path which will be required when reading the file.

All possible Directories that tin be accessed are mentioned in react-native-fs documentation.

{    "type":"Fruits",    "example":[        {"proper noun":"banana"},        {"name":"apple tree"},        {"name":"orangish"},        {"proper noun":"mango"},        {"name":"grape"}    ] }

Stride 3: In the App.js file, nosotros volition import react-native-fs and call a function named readFile which accepts file path and encoding as parameters and returns the file content. Inside "/storage/emulated/0/" I have created a folder named Information and inside is the JSON file.

Example:

App.js

import { mapValuesSeries } from 'async' ;

import React, { Component } from 'react' ;

import { Text, View, Push } from 'react-native' ;

import * as RNFS from 'react-native-fs' ;

export class App extends Component {

constructor(props) {

super (props);

this .state = {

content: naught ,

fruitType: nil ,

};

}

readFile = () => {

RNFS.readFile( '/storage/emulated/0/Information/data.json' , 'ascii' )

.then((res) => {

console.log(res);

const d = JSON.parse(res);

this .setState({ content: res, fruitType: d.type });

})

. catch ((err) => {

panel.log(err.message, err.lawmaking);

});

};

render() {

return (

<View style={{ alignItems: 'middle' }}>

<View style={{ marginVertical: 'fifteen%' }}>

<Button title= "READ" onPress={() => this .readFile()} />

</View>

<Text> { this .country.content} </Text>

<Text

fashion={{

marginVertical: '5%' ,

fontSize: 20,

color: 'light-green' ,

fontWeight: 'assuming' ,

}}>

TYPE ={ ' ' }

{ this .land.fruitType === cypher ?

'Printing READ to go the type' : this .state.fruitType}

</Text>

</View>

);

}

}

export default App;

Get-go the server past using the following control.

npx react-native run-android

Output:

To get the Directory (e.thousand. ExternalStorageDirectory) files paths we volition use the function readDir which accepts directory (for all bachelor directory types refer to the documentation of react-native-fs) type as a parameter and returns an array of objects containing file paths and information.

App.js

import { mapValuesSeries } from 'async' ;

import React, { Component } from 'react' ;

import { Text, View, Button } from 'react-native' ;

import * as RNFS from 'react-native-fs' ;

export class App extends Component {

constructor(props) {

super (props);

this .state = {

content: null ,

fruitType: null ,

};

}

readFile = () => {

RNFS.readDir(RNFS.ExternalStorageDirectoryPath)

.then((result) => {

for (permit i = 0; i < result.length; i++) {

console.log( 'GOT Consequence' , result[i]);

}

return Promise.all([RNFS.stat(effect[0].path), upshot[0].path]);

})

.then((statResult) => {

if (statResult[0].isFile()) {

return RNFS.readFile(statResult[one], 'utf8' );

}

return 'no file' ;

})

.then((contents) => {

panel.log(contents);

})

. catch ((err) => {

panel.log(err.message, err.lawmaking);

});

};

render() {

return (

<View fashion={{ alignItems: 'center' }}>

<Text>Text</Text>

</View>

);

}

}

consign default App;

Reference: https://github.com/itinance/react-native-fs


tyealannow61.blogspot.com

Source: https://www.geeksforgeeks.org/how-to-fetch-data-from-a-local-json-file-in-react-native/

0 Response to "How to Read Json File in React Native"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel