How to parse JSON from local file in React Native

Parse JSON from a local file in react-native:

JSON or JavaScript Object Notation is a widely used format for transferring data. For example, a server can return data in JSON format and any frontend application (Android, iOS or Web application) can parse and use it. Similarly, an application can send the data to a server in the same JSON format.

Sometime, we may need to test our application with local JSON files. If the server is not ready or if you want to test the app without interacting with the main server, you can use local JSON files. In this post, I will show you how to import a local JSON file and how to parse the values in a react native application.

Create one react native app :

You can create one react-native application by using the below command :

npx react-native init MyProject

Create one JSON file :

By default, this project comes with a default template. We will place the JSON file in the root directory. Open the root directory, you will find one App.js file. Create one new JSON file example.json in that folder. Add the below content to this JSON file :

{
    "name" : "Alex",
    "age" : 20,
    "subject" : [
        {
            "name": "SubA",
            "grade": "B"
        },
        {
            "name" : "SubB",
            "grade" : "C"
        }
    ]
}

It is a JSON object with three key-value pairs. The first key name is for a string value, the second key age is for a number value and the third key subject is for an array of JSON objects.

We will parse the content of this array and show in the Application UI.

JSON parsing :

We can import one JSON file in any javascript file like import name from ‘.json’. Open your App.js file and change the content as like below :

import React, { Component } from 'react';
import { Text, View } from 'react-native';
import exampleJson from './example.json'

export default class App extends Component {

  render() {
    return (

        {exampleJson.name}
        {exampleJson.age}
        {exampleJson.subject.map(subject => {
          return (

              {subject.name}
              {subject.grade}

          )
        })}

    );
  }
};

Explanation :

Here,

  • We are importing the .json file as exampleJson.
  • We can access any value for that JSON file using its key name.
  • The third key, subject is a JSON array. We are iterating through the items of this array using map().

Output :

Run it on an emulator and you will get one result like below :

React Native json parsing

Where is the color and why codevscolor ?

Long story short, I love paintings and I paint on weekends. We(me and my wife) have one Youtube channel. Below is a video that I did recently. If you love this please do subscribe to support us 😊❤️❤️