Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a JavaScript to load and parse a static JSON file in the server

I'm just starting to use javascript and json.

I need to read data (getInformation function) from a json file when processing an event in a javascript function. So I need it to be synchronic. I don't know if I am missing something in the code, or if I have to create an Request and handle the callback, or if I need to import additional javascript to use json. Because I don't know how to make it work. It doesn't work because at the end the array is empty. Any help is aprreciated.

The json file:

{"Users": [
    {"Name": "Jane",
        "Points": 67,
        "age": 23},
    {
        "Name": "Sam",
        "Points": 65,
        "age": 21}
]} 

Option 1 - Function called by another function which is processing an event:

var getInformation = function() 
{
    var path = "./data/users.json";
    var informationArray= [];
    console.log("Loading ....");
    $.getJSON(path, function(data) 
    {
        $.each(data, function(key, val) 
        {
            informationArray.push(key + '-' + val);
        });
    }); 
    return informationArray; 
}

Option 2 - Function called by another function which is processing an event:

var getInformation = function() { 
var path = "./data/users.json";
var informationArray= [];
$.ajax({
         url: path,
         async: false,
         dataType: 'json',
         success: function(response) {
         $.each(response.items,
         function(item) {
         informationArray.push(item);
         });
         informationArray.push("success");
         }
         }); 
   return informationArray; }

I have seen the following thread and tried what is there but doens't work for me. I would like to know where is the problem in my code or if require any special configuration.

Thread: Is there a version of $getJSON that doesn't use a call back?

like image 819
user2333683 Avatar asked Apr 29 '13 21:04

user2333683


People also ask

How do you parse JSON in JavaScript?

Use the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}'); Make sure the text is in JSON format, or else you will get a syntax error.

Can JavaScript parse JSON natively?

JSON is a JavaScript-based object/value encoding format that looks very close to raw JavaScript and can be very easily parsed by JavaScript code because JavaScript can effectively evaluate a JSON string and re-materialize an object from it.

Can JavaScript read JSON file?

Use the fetch() Function to Load JSON Files in JavaScript This function is only suitable for working in the web-based environment as the fetch API works only in that environment. After reading the file, we parse the data using json() function and display it.


1 Answers

When JavaScript is running in a browser it needs to make an AJAX request to the server to access a JSON file. It is possible to write the AJAX request by hand but that is complex and difficult to make work in all browsers. Instead most people use a library like jQuery. You will need to include jQuery in your web page with something like:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>

Then in any script tag lower in the html page you should be able to do something like:

$.ajax({
  url: "data/users.json",
  dataType: "json",
  success: function(response) {
    $.each(response.Users, function(item) {
      informationArray.push(item);
    });
    informationArray.push("success");
  }
});

see http://api.jquery.com/jQuery.ajax/

like image 180
olleicua Avatar answered Oct 20 '22 14:10

olleicua