CodeBlanks Logo Icon CodeBlanks

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.

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

Starter code

App.js
import AsyncStorage from '@react-native-async-storage/async-storage';

async function saveUser(user) {
  // convert user to string and save
}

async function loadUser() {
  // read string and convert to object
  return null;
}

Sample solution

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

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Fill in the blank: convert object to string

Question
await AsyncStorage.setItem('user', ____(user));
Answer
await AsyncStorage.setItem('user', JSON.stringify(user));

Explanation: You convert the object to a string with JSON.stringify.

2 Which function is used when storing an object?

App.js
await AsyncStorage.setItem('user', ?(user))
  • JSON.parse
  • toString
  • JSON.stringify Correct answer
  • parseInt

Explanation: JSON.stringify converts the object to a string.

3 Match: function and role

Term Meaning
JSON.stringify object to string
JSON.parse string to object
setItem store string

All lessons in Beginner