Hi Friends 👋,
Welcome To Infinitbility! ❤️
To convert a string to JSON in react native, just use the JSON.parse()
method it will return a JSON object based on the string.
Like the following example, we can convert strings to JSON objects, and also we can use their property.
convert object string to json object
const jsonStr = '{"name":"Infinitbility","gender":"male"}';
const jsonObj = JSON.parse(jsonStr);
console.log(jsonObj); // {name: 'Infinitbility', gender: 'male'}
console.log(jsonObj.name); // Infinitbility
convert array of object string to json array of object
const jsonStr = '[{"name":"Infinitbility","gender":"male"}]';
const jsonObj = JSON.parse(jsonStr);
console.log(jsonObj); // [0: {name: 'Infinitbility', gender: 'male'}]
console.log(jsonObj[0].name); // Infinitbility
Today, I’m going to show you How do i convert string to JSON react native, as above mentioned here, I’m going to use the JSON.parse()
method to convert string to JSON.
Let’s start today’s tutorial how do you convert string to JSON react native?
In this example, we will do
- Create a sample JSON string variable.
- Use
JSON.parse()
method to convert string to JSON - Print the Output on the screen
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":"Infinitbility","gender":"male"}';
const result = JSON.parse(str);
console.log(result); // {name: 'Infinitbility', gender: 'male'}
setJsonObj(result);
}, []);
return (
<View style={styles.container}>
{jsonObj && (
<>
<Text>{'Name => ' + jsonObj.name}</Text>
<Text>{'Gender => ' + jsonObj.gender}</Text>
</>
)}
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
backgroundColor: '#ecf0f1',
padding: 8,
},
paragraph: {
margin: 24,
fontSize: 18,
fontWeight: 'bold',
textAlign: 'center',
},
});
As above mentioned, we are taken the example of a JSON string variable, convert it into a JSON object, and printed it on the screen.
Let’s check the output.
I hope it’s help you, All the best 👍.