Kleber Mota
Kleber Mota

Reputation: 9065

JSON.parse returning unexpected token

I try parse the following JSON string (generated and returned from server) using JSON.parse:

[{"id":1,"username":"klebermo","password":"$2a$04$YYqryKrcmUQfwmbsnhA1Te0FghiYsirxVq.Wf.kChjpEm/uuky.fu","firstName":"Kleber","lastName":"Mota","email":"[email protected]","credenciais":[{"id":1,"nome":"user","autorizacoes":[{"id":1,"nome":"user","authority":"user"}]},{"id":2,"nome":"admin","autorizacoes":[{"id":2,"nome":"admin","authority":"admin"}]}],"enabled":true,"credentialsNonExpired":true,"accountNonLocked":true,"accountNonExpired":true,"authorities":[{"id":1,"nome":"user","authority":"user"},{"id":2,"nome":"admin","authority":"admin"}]}]

but I got this error:

Uncaught SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
at Object.success ((index):186)
at i (jquery-3.2.1.min.js:2)
at Object.fireWith [as resolveWith] (jquery-3.2.1.min.js:2)
at A (jquery-3.2.1.min.js:4)
at XMLHttpRequest.<anonymous> (jquery-3.2.1.min.js:4)

My javascript code where this parsing shappens:

<script th:inline="javascript">
/*<![CDATA[*/
var atributos = [];

$('.col').each(function(){
    var prop = $(this).data('prop');
    atributos.push(prop);
});

var url = '/' + $('.list').data('list') + '/list.json';

$.get(url, function(data){
    var json = JSON.parse(data);

    $.each(json.item, function(index, item){
        var row = $('<tr id='+item.id+'>');

        for(var i=0; i<atributos.length; i++) {
            if(atributos[i] == '#') {
                row.append('<td></td>');
            } else if(atributos[i] == '.') {
                var col = $('<td>');
                col.append('<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#modal_update">editar</button>');
                col.append('<button type="button" class="btn btn-primary btn-lg" class="remover" data-target="'+item.id+'">remover</button>');
                row.append(col);
            } else {
                row.append('<td>'+item[atributos[i]]+'</td>');
            }
        }

        $('table.table').find('tbody.list').append(row);
    });
});
/*]]>*/
</script>

If I try validate the JSON string in several json validation sites, and no error is displayed. The JSON is listed in the Network tab in the browser developer tool, ans it's displayed correctly too.

Anyone can give a hint of what could be wrong here?

Upvotes: 1

Views: 908

Answers (1)

ixpl0
ixpl0

Reputation: 756

It's already an object. No need to parse it. o at position 1 is the second symbol from [object Object].

Upvotes: 3

Related Questions