2

I am trying to parse an external JSON file, and then parse it in javascript but i am getting an uncaught reference error.

I first declare the .json file in my html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
    <script type="text/javascript" src="OnebusinessDataFormat_yelp.json"></script>
    <title>title</title>
  </head>
  <body>


    <div class="dropdown">
        <button onclick="myFunction()" class="dropbtn">Dropdown</button>
          <div id="myDropdown" class="dropdown-content">
            <a onclick="name()">NAME</a>
            <a onclick="address()">ADDRESS</a>
            <a onclick="bh()">BUSINESS HOURS</a>
            <a onclick="menu()">MENU</a>
            <a onclick="saf()">SERVICES and FEATURES</a>
          </div>
    </div>

    <div id="name">
        <p id="rest_name"></p>
    </div>
  </body>
</html>

I then try to parse that file in my javascript code:

var jsonFile = JSON.parse(OnebusinessDataFormat_yelp.json);
function name(){
    document.getElementById("rest_name").innerHTML = jsonFile.name;
}

but when i select name from the dropdown it does not populate the <p> element with the restaurant name.

3
  • The argument to JSON.parse() is a string containing the JSON, not a filename. Commented Mar 19, 2019 at 4:20
  • You can't use a JSON file as the src of a <script>. Commented Mar 19, 2019 at 4:21
  • OnebusinessDataFormat_yelp.json means you have a variable named OnebusinessDataFormat_yelp and it contains an object with a json property. You get the reference error because there's no variable with that name. Commented Mar 19, 2019 at 4:22

4 Answers 4

2

You need to use the Fetch API in vanilla JS if you want to get the contents of a file:

var jsonFile;
fetch("JOnebusinessDataFormat_yelp.json")
    .then(res => res.json())
    .then(data => jsonFile = JSON.parse(data));

Please also note that this line:

<script type="text/javascript" src="OnebusinessDataFormat_yelp.json"></script>

Will not work because you can't have a JSON file inside a <script> tag - JSON is JavaScript Object Notation (a string), and is a way of storing JavaScript objects in a simpler way than objects. You can only have a .js file inside a <script> tag.

Sign up to request clarification or add additional context in comments.

3 Comments

You need to use jsonFile inside the then() function, since it's asynchronous. Don't lead him down the path of trying to use jsonFile outside the callback.
Oh yes @Barmar, forgot about that.
this is for a local json file, im now getting an error saying fetch API cannot load the JSON file. Is that because it is not located on a server?
1

you can use this code to get the local json file in javascript.

use this url for more reference. $.getJSON Reference

$.getJSON("test.json", function(json) {
    console.log(json); // this will show the info it in console
});

Comments

0

I will explain to you how it work, hope it will help you think.

There are 2 types of JavaScript, Server and Client.

If your JavaScript is running on Node.js (Server), all you nee is require().

const json = require(jsonFilePath);

require() will automatically parse the JSON (.json extension file) and generate JavaScript Object for you.

If your JavaScript is running in a Browser (Client), you can't open files from user file system. Just Imagine if Javascript can open any file it want from user file system. All of our data will be in Facebook data center Description 😂.

So for obvious security reasons, you will not be able (as browser app) to open any file you want from the user file system. But you will be able to open files provided by the user like <input type="file" /> or create by yourself in specific way, other people already answered it, you can choose any solution that make sense to your app.

Comments

0

Use this

function loadJSON(callback) {   

        var xobj = new XMLHttpRequest();
            xobj.overrideMimeType("application/json");
        xobj.open('GET', 'OnebusinessDataFormat_yelp.json', true); 
        xobj.onreadystatechange = function () {
              if (xobj.readyState == 4 && xobj.status == "200") {
                // Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
                callback(xobj.responseText);
              }
        };
        xobj.send(null);  
     }

The function above will create a new instance of a XMLHttpRequest and load asynchronously the contents of OnebusinessDataFormat_yelp.json. I have gone with asynchronous but you can change the argument to false if you want a synchronous load. Thankfully all modern browsers support the native JSON.parse method. Remember our anonymous callback? here's how you use it.

function init() {
 loadJSON(function(response) {
  // Parse JSON string into object
    var actual_JSON = JSON.parse(response);
 });
}

For more details refer - https://codepen.io/KryptoniteDove/post/load-json-file-locally-using-pure-javascript

4 Comments

script.js:94 Access to XMLHttpRequest at 'file:///C:/Users/Nick/Desktop/project4/OnebusinessDataFormat_yelp.json' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
okay this works on firefox, but not chrome. also, how can i get this to use the JSON file in another fucntion? it only lets me load it inside the loadJSON function.
if you want to access this object globally use window.actual_Json = JSON.parse(response) in init function
To know about CORS and how to fix CORS issue try this link - codecademy.com/articles/what-is-cors . If this answer helps you, dont forgot to click tick mark. this may help other developers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.