0

I have no idea why I'm not able to parse this JSON file in JS using RequireJS.

var settings = require('https://api.jsonbin.io/b/5e9535d3634f8d782606be53');
var parsed = JSON.parse(settings);
var indexPar = document.createElement('p');

window.onload = testJSON();

function testJSON() {
    indexPar.innerHTML = "Full name is " + parsed.fname + " " + parsed.lname + "\nExpiration Date is " + parsed.expdate + "\nCredit Card # is " + parsed.creditcardnumber + "\nCVV is " + parsed.cvv;
}
<script type="text/javascript" src="https://requirejs.org/docs/release/2.3.6/r.js"></script>

To my knowledge, it should show this on the main HTML page:

Full name is Harrison Reeves

Expiration Date is 01/23

Credit Card # is 1234 5678 9012

CVV is 000

9
  • 1
    errors in the console? try window.onload = testJSON; Commented Apr 14, 2020 at 4:19
  • @JaromandaX That didn't do anything. I'm pretty sure that JS functions are referenced to with () at the end always, even without objects. Commented Apr 14, 2020 at 4:23
  • 1
    window.onload = testJSON(); will run testJSON() and assign the result of calling that function (undefined in this case) to window.onload ... whereas window.onload = testJSON; will call the function testJSON on the window load event - you decide which is correct Commented Apr 14, 2020 at 4:38
  • 1
    also, indexPar.innerHTML = .... etc sets the innerHTML of an element that you haven't yet inserted into the DOM ... so, nothing will display in the web page .... creating an element doesn't add it to the DOM for you, you have to decide where you want to put it Commented Apr 14, 2020 at 4:40
  • 1
    then you will need to Commented Apr 14, 2020 at 5:15

1 Answer 1

1

Check this out. Used this $.getJSON function to fetch a JSON file.

$.getJSON( "https://api.jsonbin.io/b/5e9535d3634f8d782606be53", function( parsed ) {
    window.onload = testJSON();

function testJSON() {
   $("#list").html("Full name is " + parsed.fname + " " + parsed.lname + "\nExpiration Date is " + parsed.expdate + "\nCredit Card # is " + parsed.creditcardnumber + "\nCVV is " + parsed.cvv);
}
 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>

<pre id="list"></pre>

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

3 Comments

This works great except the \n doesn't work and it uses jQuery. Is there a way to do this using pure JS? Also, why doesn't \n make a new line?
@HarrisonReeves - you use fetch or XMLHttpRequest
"\n" in HTML doesn't make a new line, unless you are in a <pre> element - HTML 101

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.