简体   繁体   中英

How can I extract a number value from a json localStorage string?

I'm new to JSON, so bear with me!

I am storing 3 numeric values in localStorage, and then I need to add them up.

The localstorage json string comes out to (with randomnly entered numbers into local storage)

    {"bookmarks3":"[{\"answer\":\"989\"}]","bookmarks4":"[{\"answer\":\"8777\"}]","bookmarks5":"[{\"answer\":\"8777\"}]"}

Here is my code:

    function bookmarkMath() {
    // Fetch input
    // Get bookmarks from LocalStorage
    var bm1 = JSON.stringify(localStorage);
    var bm2 = 10;
    var bm3 = 30;
    var bookmarksTotal = JSON.parse(bm1) + bm2 + bm3;
    // Get output id 
    var bookmarkmathResults = document.querySelector('.input-results-math');

    // Build outputs
    bookmarkmathResults.innerHTML = '';


    var name = bookmarksTotal;  

    bookmarkmathResults.innerHTML = name;
    bookmarkmathResults.style.display = 'inline-block';

    console.log(`Total is "${booksmarksTotal}"`);

    }

Local Storage output

    bookmarks3=[[{"answer":"35"}]]
    bookmarks4=[[{"answer":"355"}]]
    bookmarks5=[[{"answer":"2344"}]]

Any help would be very appreciated!!!!

No reason to stringify the JSON since you are just parsing it again later anyway.

You can easily get the value by either doing localStorage.getItem or localStorage.param

So in your above example you would do something like:

var bm1 = localStorage.getItem('bookmarks1');

Or you could just access by:

var bm1 = localStorage.bookmarks1

Your current setup is just json.parse the data which is going to return the JSON not the value associated to your key.

To get just the number just do .answer as well. So:

var bm1. = localStorage.bookmarks1[0].answer

or

var bm1 = localStorage.getItem('bookmarks1')[0].answer

Note, you are storing an array so you need to get index 0, doesn't look like you have more than one per entry.

If you want to get each number from bm1 , just iterate through the object like so:

for (var bookmark in bm1) {
    console.log(key[0].answer);
}

This will output the following to the console;

989
8777
8777

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM