Uncaught Syntaxerror: Unexpected token u in JSON at position 0

Asked

Viewed 14,930 times

3

In my html I am using Javascript to try to recover a Json object saved in localStorage. I am using Google Chrome.

First I get the value of the "name" attribute of my Json object that is in localStorage, via form, and then I run the script that should recover this object, saving it in a var. However, I have the following mistake:

Uncaught SyntaxError: Unexpected token u in JSON at position 0
    at JSON.parse (<anonymous>)
    at buscaConta (principal.html:114)
    at HTMLButtonElement.onclick (principal.html:99)
buscaConta @ principal.html:114
onclick @ principal.html:99

This is the snippet with my form and the script that retrieves the Json object by "name".

div  class="formu" id="formularioDeIdent" style="display:none">

            <p class="textoForm"> Informe seu nome: </p> 


        <form>

            <div>
                <label for="nome"> Nome: </label>
                <input type="text" id="nome" />
            </div>


            <div class="centralizar">
            <br><br>
                <button class="botaoPequeno" type="button" onClick="buscaConta()">Buscar sua conta</button>
            </div>
            <br><br>
            <div class="centralizar" style="display:none">
            <br><br>
                <button class="botaoPequeno" type="button" onClick="mudaMenu('formularioDeIdent', 'menu2')">Prosseguir</button>
            </div>

        </form>

    </div>

    <script>
        function buscaConta(){
            var name = document.getElementById('nome');

             //O ERRO OCORRE NA LINHA ABAIXO:
            console.log(JSON.parse(localStorage[nome.value]).valueOf());
            //console.log(oCliente);
        }
    </script>

The search form and Json saved in the Storage location:

inserir a descrição da imagem aqui

The code I use to save Json objects to localStorage:

<script>

            var nome = document.getElementById('nome');
            var agencia = document.getElementById('agencia');
            var conta = document.getElementById('conta');

            var obj;

            document.getElementById("enviarConta").addEventListener('click', function(){

            //Monta o objeto que será salvo

            obj = {
            nome: nome.value,
            agencia: agencia.value,
            conta: conta.value
            };

            //Mostra no console o objeto antes de ser salvo no localStorage
            console.log(obj.valueOf());
            //Salva o objeto no localStorage
            localStorage[nome.value] = JSON.stringify(obj);

            });
    </script>
  • 1

    I’m not sure, but I believe this error is related to how you saved the object in localStorage, add that part of the code to the question

  • 1

    localStorage[name.value] is Undefined, probably. test with console.log(localStorage[name.value]);

  • There is something wrong there, the key is JSON, and value is null. The key needs to be Lucas dos Santos and value should be JSON

  • Enter your code by entering the data into Localstorage

  • @Sveen Yes, I tested as you said, console.log(localStorage[name.value]), and returned Undefined. But if name.value = "Lucas dos Santos", the script should not find the Json object with the attribute name of the same value?

  • But as you can see, the data is in the localStorage...

  • But I’ll put the script to write the object as well. Just a moment

  • 1

    @Lucaspletsch the data was entered wrong. In this case, you only put the key, but no value. You will only find this object when you place the entire JSON in the search

  • @Sveen Boa. So if I enter value (set of attributes, as name, agency...?) I can do the name search?

  • Could you give me an example of how to enter value together?

  • Clear localStorage, and try with localStorage.setItem(obj.name,JSON.stringify(obj));

  • That mistake is because the code localStorage[nome.value] is not finding localStorage with the name.value

  • Put in place if(localStorage[nome.value]){&#xA; console.log(JSON.parse(localStorage[nome.value]).valueOf());&#xA; }&#xA; and you will see that there is no error

  • the problem is that you are all messing with this... already asked 3 questions with the same subject and is not able to do. Simple thing.

  • The mistake Uncaught SyntaxError: Unexpected token u in JSON at position 0... that u is of undefined... is trying to parse something that doesn’t exist.

  • But the object exists. Did you see the screen print I put up? The object is there and the console says it doesn’t. name.value is the contents of the name var, right? and that’s why I’m doing the right search? So why doesn’t the script find the Json object?

Show 11 more comments

1 answer

3


The problem was this:

there was already an element in html with id="name". So when giving a

var nome = document.getElementById('nome');

I was looking for another element of the document, not the form field I was filling out to search in localStorage.

I changed the text input id of the search form to "Nome2" and it worked!:

 <div>
       <label for="nome"> Nome: </label>
       <input type="text" id="nome2" />
 </div>

DOM does not allow Elements with duplicate Id. If you have, when doing an id search you will get the first element you find with the id passed.

Browser other questions tagged

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