I currently have some Javascript on a page template which manages some JSON data. The way I have it configured currently, the JSON data is assigned to a variable right on the page template. What I would like to do is move the JSON to an external .json file and still be able to use my variable on the page template. Currently it looks like this:
var data = [{
"fruit": "Apple",
"size": "Large",
"color": "Red"
}];
What I would like to do is create a file called data.json and then assign it as the data variable on my page template.
data.json:
{
"fruit": "Apple",
"size": "Large",
"color": "Red"
}
Page template:
var data = 'data.json';
How can I accomplish this?
Load your json in dynamic way using e.g. fetch
async function start() {
let url = 'my.json'
var data = await (await fetch(url)).json();
// ...
}
start();
Related
I am trying to create a chart using json data. Currently I have the data within my script, but I would like to link it to a separate .json file within the project folder.
This is what I have currently:
var jsonfile = {
"jsonarray": [{
"name": "Joe",
"age": 12
}, {
"name": "Tom",
"age": 14
}]
};
var labels = jsonfile.jsonarray.map(function(e) {
return e.name;
});
var data = jsonfile.jsonarray.map(function(e) {
return e.age;
});
var ctx = document.getElementById("chart");
var chart = new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets: [{
label: 'Graph Line',
data: data,
backgroundColor: 'rgba(0, 119, 204, 0.3)'
}]
}
});
Ideally, I would like the json data to be in a separate file so that it can be dynamically saved.
Thanks :)
You can use the fs module to read and write to a file
var fs = require('fs');
var jsonfile = fs.readFileSync('the/path');
//if you want to write to the file I gave you a link that shows you the way
For more information about the fs module you can check File System | Node.js v12.6.0 Documentation.
You may need to pass by JSON.stringify and JSON.parse to save your object as a string in the file and to parse the string back to an object while reading the file.
Another manner that you may consider is lightweight javascript databases such as IndexedDB which is an embedded database in the browser side, or other databases such as neDB if you want to persist data especially with an electron app.
Have many way to use with your wish
var data = {"a" : "b", "c" : "d"};
then
<script src="data.js" ></script>
or
var json = require('./data.json');
or
$.getJSON("data.json", function(json) {
console.log(json);
});
Good luck!
I have a list of data in my JSON file. I am trying to output certain strings and arrays from my JSON file via my JS. How do I go on about this? All these files are saved on my desktop.
I've tried Xhttp code. But I think I need some server going on for that, and I don't have that. Also, I'm pretty sure this should be possible without having to use a server?
PS: the json file is named: movie.json
JSON CODE
{
"movie": {
"name": "drive",
"year": "2011",
"people": {
"actors": [
{
"name": "ryan gosling"
},
{
"name": "cary mulligan"
},
{
"name": "bryan cranston"
}
]
}
}
}
JS CODE
function preload() {
var movie = load.JSON("movie.json");
}
function(movie) {
var movie = JSON.parse(movie);
console.log(movie[0].name);
console.log(movie[0].year);
console.log(movie[0].actors);
}();
drive, 2011, ryan gosling, cary mulligan, bryan cranston
var movie;
var http = new XMLHttpRequest();
xhhtp.open( "GET", "movie.json", true);
xhttp.onreadystatechange = function () {
if(http.readyState == 4 && http.status == 200) {
movie = JSON.parse(http.responseText);
}
}
http.send();
console.log(movie[0].name);
console.log(movie[0].year);
console.log(movie[0].actors);
I do not know if the code above will help you. Using XMLHttpRequest will help you fetch the json file then you can parse and sort into array. Note: you do not need a server to use XMLHttpRequest, if you have text editor like VSCode you can us it to run live HTML codes then you can get the full link to the JSON file you want to parse e.g localhost:9000/movie.json
I'm fiddling with jquery and json, basically trying to make a weather app. I want to display gifs according to the data.
Example data coming from the API:
"time": 1468261711,
"summary": "Clear",
"icon": "clear-day",
I know the possible values already so I want to make an array like if the summary object is "Clear", display sunny.gif.
What would be a common method of achieving this?
Without more example code, it's hard to advise on the best solution.
You can create an object with keys that reference the summary and values that point to the GIF.
ie:
var gifs = {
"Clear": "clear.gif",
"Sunny": "sunny.gif"
};
Now when you parse through the data from the API. You can get the relevant GIF.
var weatherObject = {
"time": 1468261711,
"summary": "Clear",
"icon": "clear-day"
}
var gif = gifs[weatherObject.summary]; // Returns clear.gif
Read more about JS Objects here.
You can have a hash object that maps the weather summary to the gif like:
var map = {
"Cloudy": {
"media": "../images/weather-cloudy.gif"
},
"Clear": {
"media": "../images/weather-sunny.gif"
}
};
On your API ajax callback you could render based on this map info:
$.get("api/weather?q=Newyork")
.done(function (data) {
var html = yourHandlebarsCompiledTemplateForExample({
apiData: data,
mappedInfo: map[data.summary]
});
$(html).appendTo("#weather-contanier");
});
Let's say I have a animals.json file with the following content:
{
"animals": {
"elephant": {
"size": "large"
},
"mouse": {
"size": "small"
}
}
}
And I'm adding that data to the scope of my controller:
animalsApp.controller('animalsCtrl', function($scope, $http){
$http.get('../../animals.json').success(function(data){
$scope.animals = data.animals;
});
});
Which works perfectly, however let's say I need to get some data from an API that I need to add to $scope.animals, which has the following data:
{
"animal_name": "Leonardo"
}
Which is returned when I go to the api with the jsons data:
http://api.someapi.com/animals/{animals.elepahant} // returns above json
Pretend {animals.elaphant} is the results I get when i loop my json, get a value from it, and get the data from a remote api with the query being a variable of mines, add results to my json and return that new modified json in $scope.animals.
So the final json would look like:
{
"animals": {
"elephant": {
"size": "large",
"name": "Leonardo"
},
"mouse": {
"size": "small",
"name": "Vader"
}
}
}
How can I achieve this?
Normally you would have an array of animals and loop through that array.
Since you have an object the principle is the same. It is important to use a closure for the loop. Will use angular.forEach() to create that closure.
Using for loops by themselves do not create a closure and can be problematic since the loop finishes long before the request responses are returned
$http.get('../../animals.json').success(function(data){
$scope.animals = data.animals;
angular.forEach(data.animals, function(v, animal_type){
var url = 'http://api.someapi.com/animals/' + animal_type;
$http.get(url).success(function(resp){
v.name = resp.animal_name;
});
});
});
There are also alternative ways to write this using chained promises.
I kept it simple for now
sample json data file
{
"Includes": {
"Employees": {
"14": {
"name": "john",
"age": 12,
"activity": {
"Count": 3502,
"RatingValue": 5
}
},
"17": {
"name": "smith",
"age": 23,
"activity": {
"Count": 232,
"RatingValue": 5
}
}
}
}
}
js was written to retrieve the nested document and stored in array
var result = [];
db.details.find().forEach(function(doc) {
var Employees = doc.Includes.Employees;
if (Employees) {
for (var key in Employees) {
var Employee = Employees[key];
var item = [];
item.push(key);
item.push(Employee.name);
item.push(Employee.age);
item.push(Employee.activity.Count);
item.push(Employee.activity.RatingValue);
result.push(item.join(","));
}
}
});
print(result);
How can we store the output of array in csv with 2 rows because the data contains 2 rows by using mongoexport. In csv output must be
14,john,12,3502,5
17,smith,23,232,5
var csv=""; //this is the output file
for(var i=0;i<result.length;i++){//loop through output
csv+=result[i]+"\n"; //append the text and a newline
}
window.open('data:text/csv;' + (window.btoa?'base64,'+btoa(csv):csv)); //open in a new window, chrome will automatically download since it is a csv.
Change that final print(result); to the following:
print(result.join("\n"));
Then call your script and direct the output to a CSV file like so:
mongo --quiet "full-path-to-script.js" > "full-path-to-output.csv"
Note: The --quiet arg suppresses the standard Mongo header output (shell version and initial database).
I created a details collection, and added your JSON document to it, and then running the modified script resulted in the following CSV file content:
14,john,12,3502,5
17,smith,23,232,5
If you want a CSV header row as well, see my nearly identical answer to your nearly identical question here: https://stackoverflow.com/a/26310323/3212415