-5

Based on the value inside the localStorage geo__location, I should show and hide an element on the page. If the value of the country is US I should show the element but hide it if it's not US.

If I run: window.localStorage.getItem("geo__location")

in console, I get this:

"{"country":"US","currency":["USD"]}"

But how can I check only the value of country inside the json?

user1941537
  • 6,097
  • 14
  • 52
  • 99
  • 3
    Not meaning to be harsh, but ~3K rep and you couldn't search for a way to parse JSON in JavaScript? – Mitya Nov 03 '20 at 10:32
  • 1
    Does this answer your question? [Parse JSON in JavaScript?](https://stackoverflow.com/questions/4935632/parse-json-in-javascript) – evolutionxbox Nov 03 '20 at 10:36
  • 2
    You already mentioned “json.parse” in the title, which is the incorrect capitalization of the `JSON.parse` method. You’re aware of this method, so why not simply use it here? – Sebastian Simon Nov 03 '20 at 10:37
  • If you know what `JSON.parse` is, then you would apply it, and not ask a question about how to use something you already know. –  Nov 03 '20 at 10:38

4 Answers4

2

You can use JSON.parse. Here goes an example.

var obj = JSON.parse('{"country":"US","currency":["USD"]}');
console.log(obj['country']);
Prime
  • 2,809
  • 1
  • 7
  • 23
2
JSON.parse(localStorage.getItem('geo__location')).country

You don't need to add window at the beginning. You parse the JSON first and then exrtact the property

2

The Answer to your question is in the header of same. localStorage only stores strings, so before putting values into localStorage use JSON.stringify(), and to read them use JSON.parse()

JSON.parse('{"country":"US","currency":["USD"]}').country
efkah
  • 1,628
  • 16
  • 30
1

Using JSON.parse:

const item = JSON.parse( window.localStorage.getItem("geo__location"))
item.country;
item.currency
Aadil Mehraj
  • 2,586
  • 1
  • 7
  • 17