How to fetch data from local JSON file on react native?

JsonReact NativeLocal Files

Json Problem Overview


How can I store local files such as JSON and then fetch the data from controller?

Json Solutions


Solution 1 - Json

Since React Native 0.4.3 you can read your local JSON file like this:

const customData = require('./customData.json');

and then access customData like a normal JS object.

Solution 2 - Json

ES6/ES2015 version:

import customData from './customData.json';

Solution 3 - Json

For ES6/ES2015 you can import directly like:

// example.json
{
    "name": "testing"
}


// ES6/ES2015
// app.js
import * as data from './example.json';
const word = data.name;
console.log(word); // output 'testing'

If you use typescript, you may declare json module like:

// tying.d.ts
declare module "*.json" {
    const value: any;
    export default value;
}

Solution 4 - Json

Use this

import data from './customData.json';

Solution 5 - Json

The following ways to fetch local JSON file-

ES6 version:

import customData from './customData.json'; or import customData from './customData';

If it's inside .js file instead of .json then import like -

import { customData } from './customData';

for more clarification/understanding refer example - Live working demo

Solution 6 - Json

maybe you could use AsyncStorage setItem and getItem...and store the data as string, then use the json parser for convert it again to json...

Solution 7 - Json

Take a look at this Github issue:

https://github.com/facebook/react-native/issues/231

They are trying to require non-JSON files, in particular JSON. There is no method of doing this right now, so you either have to use AsyncStorage as @CocoOS mentioned, or you could write a small native module to do what you need to do.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmrdedView Question on Stackoverflow
Solution 1 - JsonpeterView Answer on Stackoverflow
Solution 2 - JsonPaulMestView Answer on Stackoverflow
Solution 3 - JsonLittle RoysView Answer on Stackoverflow
Solution 4 - JsonMudassir ZakariaView Answer on Stackoverflow
Solution 5 - JsonakhtarvahidView Answer on Stackoverflow
Solution 6 - JsonclagccsView Answer on Stackoverflow
Solution 7 - JsonColin RamsayView Answer on Stackoverflow