129

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

mrded
  • 4,044
  • 2
  • 30
  • 33

7 Answers7

180

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.

jasonleonhard
  • 8,968
  • 71
  • 54
peter
  • 3,009
  • 2
  • 17
  • 15
139

ES6/ES2015 version:

import customData from './customData.json';
PaulMest
  • 9,159
  • 5
  • 46
  • 47
  • could it have any name or does it have to be `customData ` – farmcommand2 Jul 27 '17 at 21:50
  • 3
    @farmcommand2 It can be any name. `import myJsonFile from './foobar.json';` – PaulMest Jul 28 '17 at 00:25
  • 1
    I just tried with React Native 0.57, and looks like the .json extension is not necessary. – Manuel Zapata Feb 15 '19 at 20:49
  • 1
    @ManuelZapata That is correct. If you exclude the suffix, the module resolver will try different extensions until it finds one that works. More info here: https://nodejs.org/api/modules.html#modules_all_together – PaulMest Feb 17 '19 at 20:50
27

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;
}
Little Roys
  • 4,745
  • 3
  • 26
  • 28
13

Use this

import data from './customData.json';
A.L
  • 9,606
  • 9
  • 60
  • 93
Mudassir Zakaria
  • 367
  • 4
  • 15
6

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

akhtarvahid
  • 8,226
  • 2
  • 18
  • 27
3

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...

clagccs
  • 2,168
  • 2
  • 20
  • 32
1

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.

Colin Ramsay
  • 15,546
  • 8
  • 50
  • 57