Nikitc
Nikitc

Reputation: 55

Javascript, read file in folder

I have a large file format "json". I need to use this information when you open the page in a browser. the only solution - is to place the data into a variable in the ".js" file, but it turns out 5000 lines. Maybe there is an option to read data? I open the page in folder

Upvotes: 1

Views: 744

Answers (4)

Upsy
Upsy

Reputation: 41

//basic method  !! think about handling the exceptions...
 
   if (window.XMLHttpRequest) { //  Objet standard
  xhr = new XMLHttpRequest(); //  Firefox, Safari, ...
} else if (window.ActiveXObject) { //  Internet Explorer
  xhr = new ActiveXObject("Microsoft.XMLHTTP");
}

// Ajax req
xhr.onreadystatechange = function () {
 // if ok  200
  if (this.readyState == 4 && this.status == 200) {


      data = this.response
     

      // your data
      console.log(data[0].title);
  }
}
xhr.open("GET", "resc/placeholder.json", true)
xhr.responseType = "json"
xhr.send(/*prams if needed */)

Upvotes: 0

guest271314
guest271314

Reputation: 1

You can use <link> element with rel attribute set to "import", get and pass link.import.body.textContent to JSON.parse() to create javascript object from JSON.

<script>
  let json;
  function handleJSON(link) {
    json = JSON.parse(link.import.body.textContent);
  }
  window.onload = function() {
    console.log(json)
  }
</script>

<link id="json" rel="import" type="application/json" href="https://gist.githubusercontent.com/guest271314/ffac94353ab16f42160e/raw/aaee70a3e351f6c7bc00178eabb5970a02df87e9/states.json" onload="handleJSON(this)"/>

Upvotes: 0

Ronnie Smith
Ronnie Smith

Reputation: 18555

The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string.

-MDN

If you need those objects to render out your webpage / webapp you're going to have to get them to the browser. Break up the JSON. Don't forget to minify.

I think the desired architecture would be to use XHR or filesystem (if that's really your use case / local only) to grab what JSON you need on demand.

Upvotes: 1

anotherdev
anotherdev

Reputation: 2569

If you want to have the data directly, you have to put it in a .js file like you did. You could write a build rule to create this .js file from the .json file.

Another solution is using Ajax, which will allow from the js to fetch the content of the .json and store it into a variable.

Upvotes: 0

Related Questions