141

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

mrded
  • 4,674
  • 2
  • 34
  • 36

7 Answers7

189

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
  • 12,047
  • 89
  • 66
peter
  • 3,109
  • 2
  • 18
  • 15
147

ES6/ES2015 version:

import customData from './customData.json';
PaulMest
  • 12,925
  • 7
  • 53
  • 50
  • 1
    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
29

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
  • 5,383
  • 3
  • 30
  • 28
  • You cannot say `import * as data from './example.json'` because that will try to assign all inner elements as data. Instead, you must use `import data from './example.json'`. – Display name Apr 01 '23 at 00:37
13

Use this

import data from './customData.json';
A.L
  • 10,259
  • 10
  • 67
  • 98
Mudassir Zakaria
  • 387
  • 4
  • 17
9

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
  • 9,445
  • 2
  • 26
  • 29
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,224
  • 2
  • 21
  • 33
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
  • 16,086
  • 9
  • 52
  • 57