1

I am trying to parse a list of JSON files iteratively. Using PHP I have managed to compile the list of JSON files in a directly into a a single JSON object. Now I would like to parse each of these objects and output a property from each of them in HTML. I am sure that the JSON I am initially passing works. Any ideas? here is the error and the function.

enter image description here

$(document).ready(function(){
    console.log("something")
    for(var i = 2; i < Object.keys(jsTrips).length; i++){
        var data_file = "http://localhos:8080/trips/" + jsTrips[i];
        var currTrip = JSON.parse(data_file)
        document.getElementsByClassName(i).innerHTML = currJSON.start_time;
    }
    console.log("finished") 
});

ignore the missing t in localhost. The problem persists even when the typo is fixed

Thanks in advance!!

UPDATE:

The Javascript object jsTrips is formatted like this:

{2: name.json, 3:name.json, 4:name.json}

The the JSON files named in jsTrips are formatted like this:

{start_time: some start time, coords: [{lat: ##, long: ##}, {lat: ##, long: ##}...], end_time: some end time}
Tom Kaizer
  • 80
  • 10

3 Answers3

3

To address the error you see:

SyntaxError: JSON.parse: Unexpected character at Line 1 Column 1

The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. You are feeding it a URL when it is expecting [ or { as the first character. So h causes a Syntax Error.

Assuming you define the Object jsTrips someplace in your code, and this is a more basic object, I would suggest the following:

$(function(){
  console.log("Start jsTrips");
  var i = 0;
  $.each(jsTrips, function(k, v){
    if(i >= 2){
      $.getJSON("http://localhos:8080/trips/" + v, function(data_file){
        $("." + i).html(data_file.start_time);
      });
    }
    i++;
  }
  console.log("Finished");
});

This code also assumes there are HTML Elements with attributes like class="2". It would be better to update your Post with an example of the Objects and an example of the JSON being returned.

Now, if the Index of the Object is the class name, then it might look more like:

$.getJSON("http://localhos:8080/trips/" + v, function(data_file){
  $("." + k).html(data_file.start_time);
}

Again, need to know what you're sending and what you expect to get back.

jQuery.getJSON() Load JSON-encoded data from the server using a GET HTTP request.

See More: https://api.jquery.com/jquery.getjson/

Update

Now using JSONP method via $.getJSON(), this will help address CORS:

$(function() {
  var jsTrips = {
    2: "file-1.json",
    3: "file-2.json",
    4: "file-3.json"
  };
  console.log("Start jsTrips");
  $.each(jsTrips, function(k, v) {
    var url = "http://localhos:8080/trips/" + v;
    console.log("GET " + url);
    $.getJSON(url + "?callback=?", function(json) {
      $("." + k).html(json.start_time);
    });
  });
  console.log("Finished");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

As you can see, this builds the new URL from your jsTrips as expected. You can get the start_time from the JSON directly. You don't need to parse it when JSON is expected.

In regards to the new CORS issue, this is more complicated. Basically, you're not calling the same URI so the browser is protecting itself from outside code.

Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell a browser to let a web application running at one origin (domain) have permission to access selected resources from a server at a different origin. A web application makes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, and port) than its own origin.

An example of a cross-origin request: The frontend JavaScript code for a web application served from http://domain-a.com uses XMLHttpRequest to make a request for http://api.domain-b.com/data.json.

For security reasons, browsers restrict cross-origin HTTP requests initiated from within scripts. For example, XMLHttpRequest and the Fetch API follow the same-origin policy. This means that a web application using those APIs can only request HTTP resources from the same origin the application was loaded from, unless the response from the other origin includes the right CORS headers.

See more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS & https://www.sitepoint.com/jsonp-examples/

If you are unable to change the port being used for the target JSON files, which I suspect is creating the CORS issue, you can consider using JSONP method versus GET method. Comment and let me know if this is the case, and I can update the answer. Example included in update.

Hope that helps.

Community
  • 1
  • 1
Twisty
  • 30,304
  • 2
  • 26
  • 45
  • This is definitely progress. My issue now that I've implemented this code is Im getting the following error: `The Same Origin Policy disallows reading the remote resource at http://localhos:8080/trips/2016-07-02--16-01-50.json. (Reason: CORS request did not succeed).` PS: I updated the original question and added examples of the data I'm working with. – Tom Kaizer Dec 24 '18 at 21:46
  • @TomKaizer updated my answer, yet you're not being forthcoming with a lot of the details so we're only slowly moving forward. – Twisty Dec 24 '18 at 21:55
0

This will not probably be a complete answer, because I don't really understand the question. But maybe it will help.

You told us you compiled in PHP one file from several JSON files, in general, if you have object in JSON file, it will look like { ...some key-values here... }, if you have array there, it will be [ ...some key-values here... ].

So when you compile several files with objects into one, you'll get {...some key-values here...} {...some key-values here...} and JSON does not know how to parse those, it will throw error:

console.log(JSON.parse('{"key": "value"}{"key": "value"}'))

This will work just fine, only one object there:

console.log(JSON.parse('{"key": "value"}'))

So, if for some reason you really need to compile several JSON files into one, there is a solution - to make such resulting file with new lines as separators. Than in JS you can split your file by new line, and parse each line without issues.

Like so:

const arrayOfJSONs = Array(10).fill(null).map((_,i) => JSON.stringify({key: i, keyXTen: i * 10}))

// then you join them in one big file with \\n new lines as separators
const oneBigFile = arrayOfJSONs.join("\n");
console.log("oneBigFile:\n", oneBigFile)

// on the client you get your one big file, and then parse each line like so
const parsedJSONs = oneBigFile.split("\n").map(JSON.parse)
console.log("parsedJSONs\n", parsedJSONs)
Valery Baranov
  • 368
  • 3
  • 10
-1

JSON.parse take string input

Javacript fetch

$(document).ready(function(){
    console.log("something")
    for(var i = 2; i < Object.keys(jsTrips).length; i++){
        var data_file = "http://localhos:8080/trips/" + jsTrips[i];
        fetch(data_file).then((res) => res.json())
        .then((currJSON) => {                  
            // document.getElementsByClassName(i).innerHTML = currJSON.start_time;
            // update your DOM here
        })
    }
    console.log("finished") 
});

JQuery $.getJSON

$(document).ready(function(){
    console.log("something")
    for(var i = 2; i < Object.keys(jsTrips).length; i++){
        var data_file = "http://localhos:8080/trips/" + jsTrips[i];
        $.getJSON(data_file, (currJSON) => {
            // document.getElementsByClassName(i).innerHTML = currJSON.start_time;
            // Update DOM here
        });
    }
    console.log("finished") 
});
Farooq Ahmed Khan
  • 3,975
  • 3
  • 27
  • 36
  • 2
    You answer suffers from the well known issue of the `i` not being block scoped. – Taplar Dec 24 '18 at 20:24
  • ^ I'd be happy If you can fix it. – Farooq Ahmed Khan Dec 24 '18 at 20:34
  • Ref. https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – Taplar Dec 24 '18 at 20:55
  • @Taplar no way to know if `i` is out of scope for a set of Object Keys of an undefined object. – Twisty Dec 24 '18 at 20:59
  • @Twisty `document.getElementsByClassName(i)` is definitely incorrectly scoped – Taplar Dec 24 '18 at 21:00
  • @Taplar it is possible that there are no elements with that class name, but it's also possible that they exist. There might be an element by the class name of "2" or "3". I am not saying you're wrong, just that maybe we're both right. – Twisty Dec 24 '18 at 21:07