How to Convert String to Json in React Native?

Sep 20, 2022 . Admin

Today, I will let you know example of json.parse() in react native. Here you will learn string to json in react native. you will learn string to json in react native example. This article will give you simple example of convert string to json in react native. Alright, let’s dive into the steps.

In this example,I will learn to convert to string to json in react native.you can easy and simply use JSON.parse() to string to json in react native.below this example.

Step 1: Download Project

In the first step run the following command to create a project.

expo init ExampleApp
Step 2: App.js

In this step, You will open the App.js file and put the code.

import React, { useState, useEffect } from 'react';
import { Text, View, StyleSheet } from 'react-native';

export default function App() {
  const [jsonObj, setJsonObj] = useState(null);
  useEffect(() => {
    const str = '{"name":"Keval","gender":"Male"}';
    const result = JSON.parse(str);
    setJsonObj(result);
  }, []);
  return (
    
    {jsonObj && (
        <>
          <Text>{'Name => ' + jsonObj.name}</Text>
          <Text>{'Gender => ' + jsonObj.gender}</Text>
        </>
      )}
      
    
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center', 
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  paragraph: {
    margin: 24,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
  },
});
Step 3: Run Project

In the last step run your project using the below command.

expo start

You can QR code scan in Expo Go Application on mobile.

Output:

It will help you...

#React Native