1

Hy everyone !

I've stored a simple object in Async Storage in a ReactNative app. But when I get it back, it isn't correctly parsed : all keys still got the quotes marks (added by JSON.stringify() when storing it) ...

I store data like that:

    const storeData = () => {
        let myData = {
            title: 'Hummus', 
            price: '6.90',
            id: '1'
        }
        AsyncStorage.setItem('@storage_Key', JSON.stringify(myData));   
    }

and then access data like that:

    const getData= async () => {
        const jsonValue = await AsyncStorage.getItem('@storage_Key')
        console.log(jsonValue);
        return JSON.parse(jsonValue);
    }    

and my object after parsing looks like that:

    {"title":"Hummus","price":"6.90","id":"1"}

Any idea why quotes aren't removed from keys ??

Meisan Saba
  • 800
  • 2
  • 9
  • 25
filip76
  • 9
  • 1
  • 3
  • Because it's JSON! The log is correct! Are you getting any kind of error? Can you access the title, price, and id actual value? – Shayan Jan 03 '21 at 19:51
  • but after JSON.parse(), doesn't JSON turn back to simple object ?? – filip76 Jan 03 '21 at 20:49
  • It does, your problem is only that it has quotes or you can't access the data? – Shayan Jan 04 '21 at 06:35
  • I thought I couldn't access data because of the quotes 'Cause the string error message I got when trying to render data wasn't much specific ... And after hours, I saw my f!@#in typo: I wrote instead of – filip76 Jan 04 '21 at 10:26
  • Thx for your help indeed !! – filip76 Jan 04 '21 at 10:29

1 Answers1

0

That's because JSON specification says the keys should be string. What you are using is the modern representation of JSON called JSON5 (https://json5.org/). JSON5 is a superset of JSON specification and it does not require keys to be surrounded by quotes in some cases. When you stringify, it returns the result in JSON format.

Both JSON and JSON5 are equally valid in modern browsers. So, you should not be worries about breaking anything programmatically just because they look different.

You can use JSON5 as shown below and it will give you your desired Stringified result.

let myData = {
  title: 'Hummus',
  price: '6.90',
  id: '1'
}
console.log(JSON5.stringify(myData));
console.log(JSON.stringify(myData));
<script src="https://unpkg.com/json5@^2.0.0/dist/index.min.js"></script>

Like this:

// JSON5.stringify
{title:'Hummus',price:'6.90',id:'1'}

// JSON.stringify
{"title":"Hummus","price":"6.90","id":"1"}
Nishant
  • 54,584
  • 13
  • 112
  • 127
  • My bad ..., error didn't come from that quotes. I didn't understand well the error message talking about strings , and searched in the wrong direction ... In fact, error came from a f!@#in typo: I wrote instead of Thx for your help !! – filip76 Jan 04 '21 at 10:31