Print JSON.Parse

Asked

Viewed 42 times

-1

Good morning,

I have a variable that stores data from a localStorage, which in turn contains the data below:

Array[3]
0:"{"Token":-6742.075757575755,"Solicitacao":"3359659","Justificativa":"jjjj"}"
1:"{"Token":-57645.84848484848,"Solicitacao":"10","Justificativa":""}"
2:"{"Token":-57645.84848484848,"Solicitacao":"10","Justificativa":"asdasd"}"
length:3

Code:

    var tbHistoricos = window.localStorage.getItem("tbHistoricos");
    tbHistoricos = JSON.parse(tbHistoricos);

What I want is to print the content of each row per tag. For each row I print with:

tbHistoricos[numero_que_eu_quero]

But I don’t want the whole line, I want every tag individual, but the way below does not work:

tbHistoricos[numero_que_eu_quero].Token

How can I do?

  • What gives you these logs: console.log(typeof window.localStorage.getItem("tbHistoricos"), window.localStorage.getItem("tbHistoricos"));?

1 answer

2


Your problem is because the content of each position is a string and not an object, so you could not access with . Token.

$ node
> var arr = [{"Token":-6742.075757575755,"Solicitacao":"3359659","Justificativa":"jjjj"},
{"Token":-57645.84848484848,"Solicitacao":"10","Justificativa":""},
{"Token":-57645.84848484848,"Solicitacao":"10","Justificativa":"asdasd"}]

> arr[0].Token
-6742.075757575755

There in that case you need to parse each position

var arr = window.localStorage.getItem("tbHistoricos");
arr = JSON.parse(arr);
arr = arr.map(i => JSON.parse(i));
console.log(arr[0].Token);

Yes it will work properly.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.