0

I am performing a test, where I have to populate a form and take the options data from a given object that resides on an external file. The idea is to fetch this data in order to populate two drop down select lists, one for the chousen state and the other for its corresponding cities and the way to achieve this, should be by making use of the async / await methods and try and catch statements. Here's the json file data.js:

var stateLocs = {
    "Alabama":["Birmingham","Huntsvillen"],
    "California":["Los Angeles","San Diego"],
    "Georgia":["Atlanta", "Augusta"],
    "New York":["New York City","Buffalo","Rochester"]
};

And this is what I have done so far, since it retrieves me an error:

    const getDataAsync = async () => {
  try {
    const res = await fetch("/js/data.js")
    const data = await JSON.parse()

    console.log(data.results)
    data.results.map(stateLocs => console.log(stateLocs))
  } catch (err) {
    const errorObject = JSON.parse(err);
    console.log(errorObject);
  }
};
getDataAsync();

Here's the retrieved error:

Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

    getDataAsync http://localhost:3000/js/scrypts.js:9
    async* http://localhost:3000/js/scrypts.js:13
scrypts.js:9:30
    getDataAsync http://localhost:3000/js/scrypts.js:10
    AsyncFunctionNext self-hosted:690
    (Asíncrono: async)
    <anonymous> http://localhost:3000/js/scrypts.js:13

I believe this is due to the fact that the json is actually inside an object and I am not accessing it in the correct way...

  • well It took your object string and parsed as it is I did not give any error on its own jsoned = JSON.parse('{"Alabama":["Birmingham","Huntsvillen"],"California":["Los Angeles","San Diego"],"Georgia":["Atlanta", "Augusta"],"New York":["New York City","Buffalo","Rochester"]}'); – Syed Feb 23 '21 at 03:01
  • considering if the error is in parser even this silly worked yielded no error var obj = '{"Alabama":["Birmingham","Huntsvillen"],"California":["Los Angeles","San Diego"],"Georgia":["Atlanta", "Augusta"],"New York":["New York City","Buffalo","Rochester"]}'; var myJSON = JSON.stringify(obj); if (JSON.parse(myJSON)){alert('yes');} – Syed Feb 23 '21 at 03:06
  • it would be second checking what is being send from server, not everything works as charm I have noticed a lot of hops and pops with Firebase data, where they format things according their own liking. – Syed Feb 23 '21 at 03:07
  • The problem is that when I try to get the info out from the data variable, it retrieves me the unexpected character at line 1. I have also tried it out with this other walk arround without any luck: – Mariano D'Acosta Feb 24 '21 at 02:26
  • ``` const getData = async () => { try { const res = await fetch("./js/data.js"); let data = JSON.parse(); data = (stateLocs) => { for (const stateLocs in data) { if (data[stateLocs]) { console.log(`${data.stateLocs}, ${data[stateLocs]}`); } } }; } catch (err) { console.log("The request failed!"); } }; getData(); – Mariano D'Acosta Feb 24 '21 at 02:26
  • do your self a favour and fetch raw "./js/data.js" in browser using address bar. then check if string is valid json to begin with. the typical unexpected character at line 1 is synonymous of such issues. – Syed Feb 24 '21 at 16:09
  • it becomes bit fatigued and debates can go back and forth (been there done that)......some links to incorporate whats really going on – Syed Feb 24 '21 at 16:13
  • to check if string that is fetched is valid json to begin with or not. https://stackoverflow.com/a/66041874/10588650 – Syed Feb 24 '21 at 16:14
  • if its not then make a valid json then parse it :) https://stackoverflow.com/a/65346633/10588650 – Syed Feb 24 '21 at 16:16

1 Answers1

0

Here is the code that worked the charter thingy is still there but non blocking. I ran number of breakdown tests it was happening outside of request context or was a double whamy where parsing on string was run twice. the script file in below example has just the following code. No semi colones nothing else. fetch and ajax will parse them automatically once received as shown in example below.

{
    "Alabama": ["Birmingham", "Huntsvillen"],
    "California": ["Los Angeles", "San Diego"],
    "Georgia": ["Atlanta", "Augusta"],
    "New York": ["New York City", "Buffalo", "Rochester"]
}



    <!doctype html>

<html>
  <head>


  </head>

  <body>
    <h1>Hello Plunker!</h1>
  </body>
  <script>
async function getData () {
await fetch('./lib/script.js')
  .then((response) => {
    return response.json()
  })
  .then((data) => {
    console.log('fetch finished');
  console.log(data);

  })

};


function getData2(){
let xhr = new XMLHttpRequest();
xhr.open('GET', './lib/script.js');

xhr.responseType = 'json';

xhr.send();

xhr.onload = function() {
  console.log('ajax finished');
 console.log(xhr.response);  
};

};
getData();
getData2();
  </script>
</html>

Result enter image description here simply run your logic for dropdown inside last then or onload function instead of console.log as shown in above example.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Syed
  • 696
  • 1
  • 5
  • 11
  • Hi! And thank you for your answer. I have no problem to access a JSON file when it has a correct structure like is in our example. But since this is for a test purpose, I cannot modify the given data.js. file, that has this json structure, inside an object {stateLocs}. I am still stuck on this... – Mariano D'Acosta Mar 01 '21 at 09:20
  • From getData() has returned me: Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data And from he getData2() I've had: ajax finished null – Mariano D'Acosta Mar 01 '21 at 09:33
  • could you please share the whole code ..... I believe we are getting caught in the edge cases. e.g. ./lib/script.js should have nothing other than { jason data } the parser error pops up when parser encounters first actual printable character other than { – Syed Mar 01 '21 at 13:23
  • secondly I had made this mistake on my early days..... given that we are fetching json from ./lib/script.js but for some naive reasons I had also linked it into script somewhere and was loaded through onload feature of browser. so parser did not know what I did. some time browser give warning and move and other times they just play naughty kid. – Syed Mar 01 '21 at 13:26
  • if lib/script is like this var stateLocs = { "Alabama":["Birmingham","Huntsvillen"], "California":["Los Angeles","San Diego"], "Georgia":["Atlanta", "Augusta"], "New York":["New York City","Buffalo","Rochester"] }; than parser will always throw tantrum – Syed Mar 01 '21 at 13:26
  • if you cannot change it then change fetch response to response.text() or xhr.responseType = 'text' for ajax and then modify this run around to make it happen var obj = '{"Alabama":["Birmingham","Huntsvillen"],"California":["Los Angeles","San Diego"],"Georgia":["Atlanta", "Augusta"],"New York":["New York City","Buffalo","Rochester"]}'; var myJSON = JSON.stringify(obj); if (JSON.parse(myJSON)){alert('yes');} – Syed Mar 01 '21 at 13:30
  • Great! Thank you so much Syed! – Mariano D'Acosta Mar 01 '21 at 23:00