alemesa
1/30/2017 - 7:28 PM

Different ways to pull JSON

Different ways to pull JSON

-----------------ES6--------------------------
// url (required), options (optional)
fetch('https://davidwalsh.name/demo/arsenal.json').then(function(response) { 
	// Convert to JSON
	return response.json();
}).then(function(j) {
	// Yay, `j` is a JavaScript object
	console.log(j); 
  // j  variable will hold the data of the JSON object
});

-----------------Javascript-------------------
var request = new XMLHttpRequest();

request.open('GET', 'data.json', true);

request.onload = function () {
	// begin accessing JSON data here
	var data = JSON.parse(this.response);

	//Start code here
  //data variable contains the JSON already parsed
}

request.send();

-----------------jQuery-------------------(requires jQuery dependency)
$(document).ready(function () {
	$.getJSON('data.json', function (data) {
		// begin accessing JSON data here
			console.log(data[0].name);
	});
});

-----------------jQuery with Ajax----------(requires jQuery dependency)
$(document).ready(function () {
		var data;
		$.ajax({
			dataType: "json",
			url: 'data.json',
			data: data,
			success: function (data) {
				// begin accessing JSON data here
				console.log(data[0].name);
			}
		});
	});

-----------------Vue Resource----------(requires Vue & Vue Resource dependency)
// GET /someUrl
  this.$http.get('/someUrl').then(response => {

    // get body data
    this.someData = response.body;

  }, response => {
    // error callback
  });

-----------------Axios----------(requires Axios dependency)
// Performing a GET request
axios.get('https://api.github.com/users/' + username)
  .then(function(response){
    console.log(response.data); // ex.: { user: 'Your User'}
    console.log(response.status); // ex.: 200
  });  

// Performing a POST request
axios.post('/save', { firstName: 'Marlon', lastName: 'Bernardes' })
  .then(function(response){
    console.log('saved successfully')
  });  

---------------------PHP----------------------

<?php

$url = 'data.json'; // path to your JSON file
$data = file_get_contents($url); // put the contents of the file into a variable
$characters = json_decode($data); // decode the JSON feed

echo $characters[0]->name;

foreach ($characters as $character) {
	echo $character->name . '<br>';
}