I'm looking for the simplest way to loop throug a JSON file.
The Data Syntax (can't change that):
{"1":{"name":FOO","price":"1","sold":"100"},"2":{"name":"FOO","price":"1","sold":"100"}
The data is stored i a file called prices.json. How can I loop through all 7573 entrys?
Thanks..
You could simply require the json file then iterate over the properties of the object that it contains.
var prices = require('./prices.json');
for (var i in prices) {
if (prices.hasOwnProperty(i)) {
console.log(prices[i]); // do something with each item...
}
}
Related
I was trying to use the method found here (see most up-voted answer):
Google Apps Script Fastest way to find a row?
I currently use this while it does work I wanted to try the above linked method yet when I replace the below code
function AutoPopulate (evalue)
{
//uses google drive file irretator reads in JSON file and parses it to a Javascript object that we can work with
var iter = DriveApp.getFilesByName("units.json");
// iterate through all the files named units.json
while (iter.hasNext()) {
// define a File object variable and set the Media Tyep
var file = iter.next();
var jsonFile = file.getBlob().getDataAsString();
// log the contents of the file
//Logger.log(jsonFile);
}
var UnitDatabase = JSON.parse(jsonFile);
//Logger.log(UnitDatabase);
//Logger.log(UnitDatabase[1027]);
return UnitDatabase[evalue];
}
WITH THIS CODE:
function AutoPopulate (evalue)
{
//this method did not work for me but should have according to stackflow answer linked above I am trying to understand why or how I can find out why it may have thrown an error
var jsonFile = DriveApp.getFilesByName("units.json").next(),
UnitDatabase = UnitDatabase.getBlob().getDataAsString();
return UnitDatabase[evalue];
}
I get an error in the excecution indicating that there is a % at postion 0 in the JSON, between the methods I dont alter the JSON file in anyway so I dont understand why does the top method work but the bottom one does not?
For further information the idea behind the code is that I have a list of Unit numbers and model numbers that are in a spreadsheet. I then convert this to a JSON file, this however is only done when a new unit is added to the fleet. As I learned one can parse a whole JSON file into a javascript object which makes working with the data set much faster. This javascript object is used so that when a user enters a UNIT# the MODEL# is auto populated based on the JSON file.
I cannot share the JSON file as it contains client information.
Your code does not work for two reasons:
You have a typo in the line UnitDatabase = UnitDatabase.getBlob()... - it should be UnitDatabase = jsonFile.getBlob()...
If you want to retrieve a nested object from a json file - you need to parse the JSOn - otherwise it is considered a string and you can not access the nested structure
Modified working code:
function AutoPopulate2 (evalue)
{
var jsonFile = DriveApp.getFilesByName("units.json").next();
var UnitDatabase = JSON.parse(jsonFile.getBlob().getDataAsString());
return UnitDatabase[evalue];
}
Mind that this code will only work if you have a "units.json" file on your drive and if evalue is a valid 1st-level nested object of this json.
I am building an air app that needs to access data from Firebase Database using the REST API. I am able to get the data but I do not know how to get the information I need from that data.
Basically, I have an Android app and a Desktop app. The android app uploads/Modifies data and the Desktop app needs to access that data and send signals to the ESP8266 via a socket connection. I have a list of 'Lights' each light as a 'lightname', 'status' and 'pin'. I want to be able to loop through all the 'pin's.
When I try to get the data , I get this JSON:
{"-LAb_YKS9l7qQno25AY5":{"lightname":"light1","pin":"14","status":"on","timestamp":1524303808146},"-LAb_cRpsGpQfr7JbCfI":{"lightname":"light2","pin":"15","status":"on","timestamp":1524303830159},"-LAb_zbf2sYuyTtW_uEr":{"lightname":"blah","pin":"9","status":"on","timestamp":1524303921921},"-LAba68lzyG15n6anuSF":{"lightname":"dishl","pin":"7","status":"on","timestamp":1524303955946},"-LAdZW2JjQVGfLMc_sb4":{"lightname":"cxcxc","pin":"14","status":"on","timestamp":1524337092712}}
I want to loop through all the lights and access their 'pin' values.
Here is what i've tried:
for (var i:int = 0; i < e.target.data.length; i++)
{
trace(e.target.data[i]["status"]);
}
I get this error:
Property 0 not found on String and there is no default value.
Any help is greatly appreciated.
Because the e.target.data answer you get from Firebase is a String and first you need to JSON.parse(...) it to transform it into data. Then your data is not an Array, it is an Object. You loop through it as following:
// Parse the incoming data.
var aData:Object = JSON.parse(e.target.data);
// Loop through string keys of the data object.
for (var aKey:String in aData)
{
trace("");
trace(aKey);
// Assign entry reference to another local variable. This is not
// mandatory, but the following code is shorter and thus more readable.
var anEntry:Object = aData[aKey];
trace(anEntry['pin']);
trace(anEntry['status']);
trace(anEntry['lightname']);
}
If you have no use of key values, you might do it in a slightly different way:
// Parse the incoming data.
var aData:Object = JSON.parse(e.target.data);
// Loop through values of the data object while ignoring the keys.
for each (var anEntry:Object in aData)
{
trace("");
trace(anEntry['pin']);
trace(anEntry['status']);
trace(anEntry['lightname']);
}
I am trying to get a list of ID from a JSON file.
So far, the only way to access the "id" object is by using this:
console.log(photos.photosets.photoset[0].id);
As you might tell, it only gives me the correct ID of the first item.
If I try this, it gives me an "undefined":
console.log(photos.photosets.photoset.id);
No Angular, just JavaScript.
for (i = 0; i < photos.photosets.length; i++) {
console.log(photos.photosets.photoset[i].id
}
You will need to iterate array of photoset's and produce new array of ids from it. Array.prototype.map is convenient in this case:
var ids = photos.photosets.photoset.map(function(obj) {
return obj.id;
});
I want to store the result from a call to a Domino Access Service (DAS) in a localStorage however when I try to convert the result object to a JSON string I get an error.
With DAS you get the result as an Array e.g.:
[
{
"#entryid":"1-CD90722966A36D758025725800726168",
"#noteid":"16B46",
Does anyone know how I get rid of the square brackets or convert the Array quickly to a JSON object?
Here is a snippet of my code:
var REST = "./myREST.xsp/notesView";
$.getJSON(REST,function(data){
if(localStorage){
localStorage.setItem('myCatalog',JSON.stringify(data));
}
});
Brackets are part of the JSON syntax. They indicate that this is an array of objects. And as you point to a view it is very likely that you would get more than one object back (one for each entry in the view).
So if you are only interested in the first element you could do this:
var REST = "./myREST.xsp/notesView";
$.getJSON(REST,function(data){
if(localStorage){
var firstRecord = data[0] || {};
localStorage.setItem('myCatalog',JSON.stringify(firstRecord));
}
});
Otherwise, you would need to define a loop to handle each of the objects :-)
/John
Any built-in ready-to-use solution in Kendo UI to parse JSON data according to schema.model?
Maybe something like kendo.parseData(json, model), which will return array of objects?
I was searching for something like that and couldn't find anything built-in. However, using Model.set apparently uses each field's parse logic, so I ended up writing this function which works pretty good:
function parse(model, json) {
// I initialize the model with the json data as a quick fix since
// setting the id field doesn't seem to work.
var parsed = new model(json);
var fields = Object.keys(model.fields);
for (var i=0; i<fields.length; i++) {
parsed.set(fields[i], json[fields[i]]);
}
return parsed;
}
Where model is the kendo.data.Model definition (or simply datasource.schema.model), and json is the raw object. Using or modifying it to accept and return arrays shouldn't be too hard, but for my use case I only needed a single object to be parsed at a time.
I actually saw your post the day you posted it but did not have the answer. I just needed to solve this problem myself as part of a refactoring. My solution is for DataSources, not for models directly.
kendo.data.DataSource.prototype.parse = function (data) {
return this.reader.data(data);
// Note that the original data will be modified. If that is not what you want, change to the following commented line
// return this.reader.data($.extend({}, data));
}
// ...
someGrid.dataSource.parse(myData);
If you want to do it directly with a model, you will need to look at the DataReader class in kendo.data.js and use a similar logic. Unfortunately, the DataReader takes a schema instead of a model and the part dealing with the model is not extracted in it's own method.