142

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

8 Answers 8

200

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.

Sign up to request clarification or add additional context in comments.

7 Comments

Is this syntax still supported ? because i can't use this syntax in my code.
Seems to work with React Native 0.26.2 for iOS. You might want to check with react-native -v and try reading the package.json.
customData only storing first 3500 character of file customData.json, Any other way to load large file @peter
@Akki Divide it into multiple smaller files?
It works perfectly - Q: Why can't I use import syntax instead?
|
156

ES6/ES2015 version:

import customData from './customData.json';

4 Comments

could it have any name or does it have to be customData
@farmcommand2 It can be any name. import myJsonFile from './foobar.json';
I just tried with React Native 0.57, and looks like the .json extension is not necessary.
@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: nodejs.org/api/modules.html#modules_all_together
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;
}

1 Comment

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

Use this

import data from './customData.json';

Comments

10

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

Comments

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

Comments

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.

Comments

0

I have the same requirement like above I have found the above mentioned ways helpful just to add more clarity and I have followed below ways to access json array from a .js file or .json file like below

1st Method :

Step - 1: Create a js file like below and add the custom data into that json array like below

data.js

export const DATA = [
    {
      id: 1,
      title: 'The Hunger Games'
    },
    {
      id: 2,
      title: 'Harry Potter and the Order of the Phoenix'
    },
    {
      id: 3,
      title: 'To Kill a Mockingbird'
    },
    {
      id: 4,
      title: 'Pride and Prejudice'
    },
    {
      id: 5,
      title: 'Twilight'
    },
    {
      id: 6,
      title: 'The Book Thief'
    },
    {
      id: 7,
      title: 'The Chronicles of Narnia'
    },
    {
      id: 8,
      title: 'Animal Farm'
    },
    {
      id: 9,
      title: 'Gone with the Wind'
    },
    {
      id: 10,
      title: 'The Shadow of the Wind'
    },
    {
      id: 11,
      title: 'The Fault in Our Stars'
    },
    {
      id: 12,
      title: "The Hitchhiker's Guide to the Galaxy"
    },
    {
      id: 13,
      title: 'The Giving Tree'
    },
    {
      id: 14,
      title: 'Wuthering Heights'
    },
    {
      id: 15,
      title: 'The Da Vinci Code'
    }
  ];
  
  export default DATA;

Step - 2: Now accessing and showing in a list from App.js file so first I have imported like below and showing in a list

import DATA from './data';

App.js

import React from 'react';
import DATA from './data';
import { SafeAreaView,StyleSheet, View, Text}  from 'react-native';

const App = () => {

  return (
    <SafeAreaView style={{flex:1}}>
    <View style={{ flex: 1, backgroundColor: 'white' }}>
        {DATA.map((item)=> 
        {return(
          <View style={{flex:1,borderBottomColor:'red',borderBottomWidth:2,marginHorizontal:12,justifyContent:'center'}} key={item.id}>
           <Text numberOfLines={1} style={{fontSize: 24, fontWeight: '400'}}>{item.title}</Text>
        </View>
        )})}
    </View>
    </SafeAreaView>
)
}

and then below screenshot is the result for both the methods followed. Just to add both App.js and data.js, items.json are present in the same folder.

2nd Method :

Step - 1: Create a json file like below and add the custom data into that json array like below

items.json

[
    {
      "id": 1,
      "title": "The Hunger Games"
    },
    {
      "id": 2,
      "title": "Harry Potter and the Order of the Phoenix"
    },
    {
      "id": 3,
      "title": "To Kill a Mockingbird"
    },
    {
      "id": 4,
      "title": "Pride and Prejudice"
    },
    {
      "id": 5,
      "title": "Twilight"
    },
    {
      "id": 6,
      "title": "The Book Thief"
    },
    {
      "id": 7,
      "title": "The Chronicles of Narnia"
    },
    {
      "id": 8,
      "title": "Animal Farm"
    },
    {
      "id": 9,
      "title": "Gone with the Wind"
    },
    {
      "id": 10,
      "title": "The Shadow of the Wind"
    },
    {
      "id": 11,
      "title": "The Fault in Our Stars"
    },
    {
      "id": 12,
      "title": "The Hitchhiker's Guide to the Galaxy"
    },
    {
      "id": 13,
      "title": "The Giving Tree"
    },
    {
      "id": 14,
      "title": "Wuthering Heights"
    },
    {
      "id": 15,
      "title": "The Da Vinci Code"
    }
  ]
  

Step - 2: Now accessing and showing in a list from App.js file so first I have imported like below and showing in a list

import DATA from './items.json';

App.js

import React from 'react';
import DATA from './items.json';
import { SafeAreaView,StyleSheet, View, Text}  from 'react-native';

const App = () => {

  return (
    <SafeAreaView style={{flex:1}}>
    <View style={{ flex: 1, backgroundColor: 'white' }}>
        {DATA.map((item)=> 
        {return(
          <View style={{flex:1,borderBottomColor:'red',borderBottomWidth:2,marginHorizontal:12,justifyContent:'center'}} key={item.id}>
           <Text numberOfLines={1} style={{fontSize: 24, fontWeight: '400'}}>{item.title}</Text>
        </View>
        )})}
    </View>
    </SafeAreaView>
)
}

export default App;

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.