I had to read a json file by javascript during an interview.
The json file is almost like this:
{ apple: {price: 1}, banana: {price: 2} }
I have got some solutions like:
- read it by the help of ajax method
- modify json file like "var json= { apple: {price: 1}, banana: {price: 2} }" and load it into HTML just like a javascript file, so I can read it as a global variable
However when I asked the Interviewer, he gave me the hints:
load json file to html using script tag like this:
script type="application/json" src="scripts/data.json"
then read the data in your js file by
eval(json)
I was confused: how could I access the data just by loading it as script tags without modifing?