React Native
JSON serialize
Learn to store objects with JSON.stringify and parse.
Storing objects with JSON
AsyncStorage stores only strings; it cannot store objects or arrays. But you can convert an object to a string and store it. For this you use JSON.stringify. The object is written to a key as a string.
const user = { name: 'Alex', age: 28 };
await AsyncStorage.setItem('user', JSON.stringify(user));
Here the user object is first converted to a string with JSON.stringify, then stored with setItem. The stored string looks like: '{"name":"Alex","age":28}'. The string preserves any object structure.
Exercise Your turn: store and read an object
In the saveUser function convert the user object with JSON.stringify and save it with AsyncStorage.setItem('user', ...). In the loadUser function read with AsyncStorage.getItem('user') and convert back with JSON.parse.
Show example solution
import AsyncStorage from '@react-native-async-storage/async-storage';
async function saveUser(user) {
await AsyncStorage.setItem('user', JSON.stringify(user));
}
async function loadUser() {
const raw = await AsyncStorage.getItem('user');
return JSON.parse(raw);
}
Reading back with JSON.parse
To convert the stored string back to an object you use JSON.parse. You pass the string read by getItem to JSON.parse; the result is an object. This way you can access the object's properties normally.
const raw = await AsyncStorage.getItem('user');
const user = JSON.parse(raw);
console.log(user.name);
If the string is null (key not found) JSON.parse(null) still returns null; it does not error. But if a corrupted string is given it throws. Therefore using try/catch can be safer.
Test yourself
-
Fill in the blank: convert object to string
await AsyncStorage.setItem('user', ____(user));
Show answer
await AsyncStorage.setItem('user', JSON.stringify(user));
-
Which function is used when storing an object?
await AsyncStorage.setItem('user', ?(user))
- JSON.parse
- toString
- JSON.stringify
- parseInt
Show answer
JSON.stringify — JSON.stringify converts the object to a string.
-
Match: function and role
- JSON.stringify
- object to string
- JSON.parse
- string to object
- setItem
- store string
Next lesson: Summary - Async Storage