franz1
franz1

Reputation: 351

How to properly parse a JSON file to use it through the JQuery Ajax method?

I created the following JSON array:

[
  {
    "nome": "Aldo Maria",
    "indirizzo": "Viale Europa 1",
    "telefono": "3397889034"
  },
  {
    "nome": "Maria13",
    "indirizzo": "Viale Europa 1",
    "telefono": "3397889034"
  }
]

and I have a Javascript file in which I want to cycle the two elements of this array. I want to do that by using the Jquery ajax method explained here.

In other terms, I supposed I should use the following sintax:

$(selector).getJSON(url,data,success(data,status,xhr))

I'm trying to apply that and wrote the following snippet into my javascrpt file, where I want to cycle the elements of the JSON array in order to display a table in which the user get back data about name, address and phone number of other people):

function validateTelefono() { setTimeout(function () {

   var data = JSON.parse(data);

   $.getJSON("I wrote the patthern of the JSON file 
              here", 
   function(){
      for (var i=0;  i < data.length; i++){
        $("#tbody").append("<tr>");
        $("#tbody").append("<td>" + data.nome[i] + "</td>");
        $("#tbody").append("<td>" + data.indirizzo[i] + "</td>");
        $("#tbody").append("<td>" + data.telefono[i] + "</td>");
        $("#tbody").append("</tr>");                        
                }
            );

For the sake of completeness, this is the whole code instead:

function validateTelefono() {


    console.log("function validateTelefono has been activated");
    if ($("#inlineFormInputTelefono").val() == "") {
        $("#errorLogTelefono").show();
    } else {
        $("#errorLogTelefono").hide();

        $("#cercaTelefono").prop("disabled", true);

        $("#tbody").empty();


        setTimeout(function () {

               var data = JSON.parse(data);

            $.getJSON(
                "D:\Unknown\array.json",

                //success
                function(){
                    console.log(data);

                    for (var i=0;    i < data.length; i++){       
                        $("#tbody").append("<tr>");
                        $("#tbody").append("<td>" + data.nome[i] + "</td>");
                        $("#tbody").append("<td>" + data.indirizzo[i] + "</td>");
                        $("#tbody").append("<td>" + data.telefono[i] + "</td>");
                        $("#tbody").append("</tr>");
                    }
                }
            );

            $("#tabella").show();

            $("#cercaTelefono").prop("disabled", false);
        }, 1000);
    }
}

While opening the page in the browser I get a:

Uncaught SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse ()

It's referred to the following line of code:

            var data = JSON.parse(data);

I suppose the error is the data inside the parenthesis.

What I should write instead of "data"? Or is there any other reason why the Jquery method doesn't work?

1) I deleted the following line of code and the error message above disappeared (thank you for the suggestion):

var data = JSON.parse(data);

I got this other error instead after I did it:

enter image description here

This was caused by the syntax of the url in the url parameter of the getJSON method: the whole path ("D:\Unknown\array.json") wasn't recognized for it doesn't live "inside" the folder where my javascript file is located ("Unknown"); instead, it's referring to an external folder ("D"). in other terms, I edited the url this way:

"array.json"

"array.jason" is located in the same folder of the javascript file ("Unknown") which it's been used by. So the correct syntax of the whole snippet is the following:

$.getJSON(

                "array.json",

                function(data){

                    for (var i=0; i < data.length; i++){                        

                        $("#tbody").append("<tr>");
                        $("#tbody").append("<td>" + data[i].nome + "</td>");
                        $("#tbody").append("<td>" + data[i].indirizzo + "</td>");
                        $("#tbody").append("<td>" + data[i].telefono + "</td>");
                        $("#tbody").append("</tr>");
                    }
                }
            );

Upvotes: 0

Views: 134

Answers (2)

buffy
buffy

Reputation: 546

The error Uncaught SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse () is caused by the path to the json file. You have to write it as \\ because \ will initiate an escape sequence. So you are currently trying to escape the U in Unknown.

Upvotes: 0

Pedro Serpa
Pedro Serpa

Reputation: 161

No need to parse as JSON because it already is in JSON format. But don't forget that the request returns an array, so (mind the data.key[i] change to data[i].key):

 $.getJSON("URL-TO-JSON", 
       function(data){
          for (var i=0;  i < data.length; i++){
            $("#tbody").append("<tr>");
            $("#tbody").append("<td>" + data[i].nome + "</td>");
            $("#tbody").append("<td>" + data[i].indirizzo + "</td>");
            $("#tbody").append("<td>" + data[i].telefono + "</td>");
            $("#tbody").append("</tr>");                        
          }
    });

Upvotes: 1

Related Questions