Printing object from Local Storage - javascript

I have a an expenses form which saves data to the Browser local storage. I have abutton on the page below the form so that after you fill in in the form you can then click to print out the data in a nice format.
I have to use the JSON data in the local storage due to the functionality of my app.
I am using the js variable to grab the data from local storage:
var my_expenses = localStorage.getItem('my_expenses');
Here is the entry in my browser local storage, with the unminified value.
Key:my_expenses
Value:
{
"income": {
"1": {
"name": "Pay (after tax)",
"freq": "26",
"value": "233"
},
"2": {
"name": "Partners take home pay",
"freq": "4",
"value": "10"
},
"3": {
"name": "Bonuses/overtime",
"freq": "26",
"value": "30"
},
"4": {
"name": "Income from savings and investments",
"freq": "1",
"value": "50"
},
"5": {
"name": "Child support received ",
"freq": "12",
"value": "40"
}
},
"outgoings": {
"1": {
"name": "Electricity",
"freq": "4",
"value": "0"
},
"2": {
"name": "Gas",
"freq": "4",
"value": "0"
},
"3": {
"name": "Water",
"freq": "4",
"value": "0"
},
"4": {
"name": "Internet",
"freq": "4",
"value": "0"
},
"5": {
"name": "Telephone",
"freq": "4",
"value": "0"
},
"6": {
"name": "Car Insurance",
"freq": "1",
"value": "0"
}
}
}
According to Print.js you can print JSON data like so (including my variable with my local storage data):
<button type="button" onclick="printJS({printable: my_expenses, properties: ['name', 'freq', 'value'], type: 'json'})">
Print JSON Data
For some reason I am getting an error in my console and I cant figure it out and no dialogue opens for printing.
Uncaught Error: Missing printable information.
at init (print.min.js:1)
at HTMLButtonElement.onclick ((index):156)
I think it may be the structure of my JSON in the local storage?. any help would be deeply appreciated.
Tried Using JSON.parse() like so:
var my_expenses = JSON.parse(localStorage.getItem("my_expenses"));
before I added JSON parse. I was getting the wrror and this was the output of the local storage in the console.
after I added it this was the output and the print button seemed to work:
But the print dialogue has no data?
How the object is created and the local storage functions:
//Set the default incomes and outgoings here
var defaultsObj = {
'income':{
1:{name:"Pay (after tax)",freq:52,value:0},
2:{name:"Partners take home pay",freq:4,value:0},
3:{name:"Bonuses/overtime",freq:26,value:0},
4:{name:"Income from savings and investments",freq:1,value:0},
5:{name:"Child support received ",freq:12,value:0}
},'outgoings':{
1:{name:"Electricity",freq:4,value:0},
2:{name:"Gas",freq:4,value:0},
3:{name:"Water",freq:4,value:0},
4:{name:"Internet",freq:4,value:0},
5:{name:"Telephone",freq:4,value:0},
6:{name:"Car Insurance",freq:1,value:0}
}
};
//Functions to store and retrieve objects from localstorage
function ls_store(name,o){
localStorage.setItem(name, JSON.stringify(o));
};
function ls_read(name){
return JSON.parse(localStorage.getItem(name));
};
function set_defaults(){
ls_store('my_expenses',defaultsObj);
expensesObj = ls_read('my_expenses');
}
//If our localstroage items are empty let's store the defaults
if(ls_read('my_expenses')==null){
set_defaults();
}

You dont save an array and printjs wait for an array.
Try to save into two differents array, first, to see the result into your pdf.
If data is displayed for first array you must : call two times printjs, one for first array and another for second array OR combine theses two array into a single and maybe adding an attribut to disting if is incombe or outcome.

Related

JSON weird format access data

This is a JSON snip that is created in WooCommerce by a plugin that adds some metadata. I cannot change the formatting of this JSON because it is generated by a plugin. The problem is that the keys and the values are added in a weird way. I am iterating through the line_items and statically referencing this data which I don't want to do, I would like to know if there is a smart way to reference for example:
"key": "_cpo_product_id",
"value": "3572",
if this was formatted correctly it would be: "_cpo_product_id": "3572" and not have "value" as a key, and it would be accessed by: foo.line_items[i]._cpo_product_id
but with this configuration I am a bit lost, I am sure there is an easy way to find the value for a specific key. I am doing this on Google app scripts, but a solution in JavaScript should suffice.
JSON snip:
"line_items": [
{
"id": 749,
"name": "Dune",
"product_id": 3572,
"variation_id": 0,
"quantity": 1,
"tax_class": "",
"subtotal": "149.54",
"subtotal_tax": "31.40",
"total": "149.54",
"total_tax": "31.40",
"taxes": [
{
"id": 24,
"total": "31.403148",
"subtotal": "31.403148"
}
],
"meta_data": [
{
"id": 11919,
"key": "_cpo_product_id",
"value": "3572",
"display_key": "_cpo_product_id",
"display_value": "3572"
},
{
"id": 11920,
"key": "_add-to-cart",
"value": "3572",
"display_key": "_add-to-cart",
"display_value": "3572"
},

How should I access the JSON Array having a numeric key?

{
"2": [{
"name": "Jeevan",
"age": "7"
},
{
"name": "Jeet",
"age": "8"
}],
"school": "Kendriya Vidyalaya"
}
I am having this JSON stored in variable named Obj. I would like to access individual JSON Objects inside of JSON Array which has a a key as "2".
Please help me to access the same.
As far as conventional way is considered i.e
Obj.key, it is not applicable here because Obj.2 or Obj."2" is not allowed.
I believe you are working with javascript.
Try to access the date like this:
array = Obj["2"]
This should work
var o = { "2": [{ "name": "Jeevan", "age": "7" }, { "name": "Jeet", "age": "8" } ], "school": "Kendriya Vidyalaya" };
o["2"];
o["school"]

Using underscore.js to find values in deeply nested JSON

I'm pretty new to Javascript, and I just learned about underscore.js. I have a deeply nested JSON object, and I need to use underscore to find key/value pairs, which I will then use to populate various HTML tables. If the structure was more shallow, using something like _.pluck would be easy, but I just don't know how to traverse past the first couple of nesting levels (i.e. surveyGDB, table, tablenames). The JSON object comes from an XML that is comprised of multiple nesting structures (mashed up from different database tables).
var JSONData =
"surveyGDB": {
"filename": "..\\Topo\\SurveyGeoDatabase.gdb",
"table": {
"tablename": [
{
"#text": "SurveyInfo\n ",
"record": {
"OBJECTID": "1",
"SiteID": "CBW05583-345970",
"Watershed": "John Day",
"VisitType": "Initial visit",
"SurveyInstrument": "Total Station",
"ImportDate": "2015-07-22T09:08:42",
"StreamName": "Duncan Creek",
"InstrumentModel": "TopCon Magnet v2.5.1",
"FieldSeason": "2015"
}
},
{
"#text": "QaQcPoints\n ",
"record": [
{
"OBJECTID": "1",
"TIMESTAMP": "2015-07-22T09:18:43",
"Code": "tp",
"Count": "357"
},
{
"OBJECTID": "2",
"TIMESTAMP": "2015-07-22T09:18:43",
"Code": "tb",
"Count": "92"
},
{
"OBJECTID": "3",
"TIMESTAMP": "2015-07-22T09:18:43",
"Code": "to",
"Count": "8"
},
{
"OBJECTID": "4",
"TIMESTAMP": "2015-07-22T09:18:43",
"Code": "bl",
"Count": "279"
},
{
"OBJECTID": "5",
"TIMESTAMP": "2015-07-22T09:18:43",
"Code": "bf",
"Count": "18"
}
]
},
{
"#text": "QaQcPolygons\n ",
"record": [
{
"OBJECTID": "1",
"TIMESTAMP": "2015-07-22T09:43:08",
"SurveyExtentCount": "",
"WaterExtentCount": "",
"ChannelUnitsCount": "",
"ChannelUnitsUnique": ""
},
{
"OBJECTID": "2",
"TIMESTAMP": "2015-07-22T13:35:15",
"SurveyExtentCount": "1",
"WaterExtentCount": "1",
"ChannelUnitsCount": "21",
"ChannelUnitsUnique": "21"
}
]
}
]
}
}
}
For instance, I wanted all of the values for 'Code' in the 'QaQCPoints' table, so I tried:
var codes = _.flatten(_.pluck(JSONData.surveyGDB.table.tablename[1].record[0], "Code" ));
console.log(codes);
In the console, this returns an array with a length of 5, but with blank values.
What am I doing wrong?
I'd also rather search for the 'Code' values in the table based on something like the '#text' key value, instead of just using it's position in the object.
If I understood you correctly, you want to always search the record array within JSONData.surveyGDB.table.tablename array for some queries. This means you need to find the record based on some parameter and return something from the found record.
Do note that the record property is sometimes an array and sometimes an object (for table SurveyInfo) in your example so I'll assume you need to take this into account.
You can make a small function to extract data and handle both objects and arrays:
function extract(record, prop) {
if (Array.isArray(record)) {
return _.pluck(record, prop);
} else {
return record[prop];
}
}
Usage example:
I wanted all of the values for 'Code' in the 'QaQCPoints' table.
I'd also rather search for the 'Code' values in the table based on something like the '#text' key value, instead of just using it's position in the object.
To achieve this you first find a record using _.find, and then extract Code values from it using the method above:
var table = JSONData.surveyGDB.table.tablename;
// find an item that has `#text` property equal to `QaQcPoints`
var item = _.find(table, function(r) {
return r['#text'] === 'QaQcPoints';
});
// extract codes from the found item's record property
var code = extract(item.record, 'Code');
// output ["tp", "tb", "to", "bl", "bf"]
Running sample:
var JSONData = {
"surveyGDB": {
"filename": "..\\Topo\\SurveyGeoDatabase.gdb",
"table": {
"tablename": [{
"#text": "SurveyInfo",
"record": {
"OBJECTID": "1",
"SiteID": "CBW05583-345970",
"Watershed": "John Day",
"VisitType": "Initial visit",
"SurveyInstrument": "Total Station",
"ImportDate": "2015-07-22T09:08:42",
"StreamName": "Duncan Creek",
"InstrumentModel": "TopCon Magnet v2.5.1",
"FieldSeason": "2015"
}
}, {
"#text": "QaQcPoints",
"record": [{
"OBJECTID": "1",
"TIMESTAMP": "2015-07-22T09:18:43",
"Code": "tp",
"Count": "357"
}, {
"OBJECTID": "2",
"TIMESTAMP": "2015-07-22T09:18:43",
"Code": "tb",
"Count": "92"
}, {
"OBJECTID": "3",
"TIMESTAMP": "2015-07-22T09:18:43",
"Code": "to",
"Count": "8"
}, {
"OBJECTID": "4",
"TIMESTAMP": "2015-07-22T09:18:43",
"Code": "bl",
"Count": "279"
}, {
"OBJECTID": "5",
"TIMESTAMP": "2015-07-22T09:18:43",
"Code": "bf",
"Count": "18"
}]
}, {
"#text": "QaQcPolygons",
"record": [{
"OBJECTID": "1",
"TIMESTAMP": "2015-07-22T09:43:08",
"SurveyExtentCount": "",
"WaterExtentCount": "",
"ChannelUnitsCount": "",
"ChannelUnitsUnique": ""
}, {
"OBJECTID": "2",
"TIMESTAMP": "2015-07-22T13:35:15",
"SurveyExtentCount": "1",
"WaterExtentCount": "1",
"ChannelUnitsCount": "21",
"ChannelUnitsUnique": "21"
}]
}]
}
}
}
function extract(record, prop) {
if (Array.isArray(record)) {
return _.pluck(record, prop);
} else {
return record[prop];
}
}
var table = JSONData.surveyGDB.table.tablename;
var item = _.find(table, function(r) {
return r['#text'] === 'QaQcPoints';
});
console.dir(item);
var code = extract(item.record, 'Code');
console.log(code);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
You have a two stage problem. Stage one is figuring out which table is QaQcPoints. If that's always JSONData.surveyGDB.table.tablename[1], you're good.
The next stage is getting your data out. You can use native array manipulation most of the time (unless you're on really old browsers). So:
var table = JSONData.surveyGDB.table.tablename[1].record;
var codeArray = table.map(function(val) { return val.Code; });
Will do the trick.

json data retrieve by jquery

How can I get the id of info1 or info2 with each information of the inside loop by jquery loop. Fo example I want to get id 1 from info1 then all the information within id 1 similarly same as from info2. I need the output to show in the browser.
var data = {
"info1": {
"1": {
"clientname": "ruhul yahoo",
"clientemail": "ruhul080#yahoo.com",
"clientusername": "ruhulya"
},
"2": {
"clientname": "kaosar yahoo",
"clientemail": "kaosar080#yahoo.com",
"clientusername": "kaosar"
}
},
"info2": {
"3": {
"id": "24",
"receiver": "5",
"content": "chat system",
"time": "2015-08-19 12:09:19"
},
"4": {
"id": "23",
"receiver": "4",
"content": "chat system",
"time": "2015-08-19 12:09:19"
}
},
}
Thanks in advance.
Iterate the json array and access the object like the following code.
var data = {
"info1": {
"1": {
"clientname": "ruhul yahoo",
"clientemail": "ruhul080#yahoo.com",
"clientusername": "ruhulya"
},
"2": {
"clientname": "kaosar yahoo",
"clientemail": "kaosar080#yahoo.com",
"clientusername": "kaosar"
}
},
"info2": {
"3": {
"id": "24",
"receiver": "5",
"content": "chat system",
"time": "2015-08-19 12:09:19"
},
"4": {
"id": "23",
"receiver": "4",
"content": "chat system",
"time": "2015-08-19 12:09:19"
}
},
};
for(var j in data){
for(var k in data[j]){
console.log(data[j][k]);
}
}
Your browser's Console will log the following objects if you run the above example.
Object {clientname: "ruhul yahoo", clientemail: "ruhul080#yahoo.com", clientusername: "ruhulya"}
Object {clientname: "kaosar yahoo", clientemail: "kaosar080#yahoo.com", clientusername: "kaosar"}
Object {id: "24", receiver: "5", content: "chat system", time: "2015-08-19 12:09:19"}
Object {id: "23", receiver: "4", content: "chat system", time: "2015-08-19 12:09:19"}
Then you can access the values like a normal object console.log(data[j][k].clientname);
This function will find you the first instance of a variable name in the object. If you need to find a variable in a specific path you could amend this function fairly easily to do that. Certainly the function as is passes the test case you've provided.
function findVar(data, varName) {
for (var i in data) {
if (i === varName) return data[i];
if (typeof (data[i]) === 'object') {
var findResult = findVar(data[i], varName)
if (typeof(findResult) !== 'undefined')
{
return findResult;
}
}
}
return undefined;
}
Firstly, This is not a valid JSON, Rmove the last , before last {
Secondly , parse it as a JSON and get the info as
data.info1[1].clientname
var data = JSON.parse('{"info1":{"1":{"clientname":"ruhul yahoo","clientemail":"ruhul080#yahoo.com","clientusername":"ruhulya"},"2":{"clientname":"kaosar yahoo","clientemail":"kaosar080#yahoo.com","clientusername":"kaosar"}},"info2":{"3":{"id":"24","receiver":"5","content":"chat system","time":"2015-08-19 12:09:19"},"4":{"id":"23","receiver":"4","content":"chat system","time":"2015-08-19 12:09:19"}}}');
alert(data.info1[1].clientname);
alert(data.info1[2].clientname);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
You can iterate over this object like this
for(var i in data){
for(var j in data[i]){
console.log(data[i][j]);
}
}

Convert JSON data to HTML table

I have a JSON code like
{
"id": 114363527,
"userId": "1",
"uploadedBy": "JaisonJustus",
"dataSource": "gdocs",
"rowcount": "3",
"colcount": "3",
"data": {
"0": {
"rowName": "",
"rowId": "2",
"colName": "Category Name",
"colId": "A",
"value": "Beverages"
},
"1": {
"rowName": "",
"rowId": "2",
"colName": "Quantity",
"colId": "B",
"value": "925"
},
"2": {
"rowName": "",
"rowId": "2",
"colName": "Amount",
"colId": "C",
"value": "$277"
},
"3": {
"rowName": "",
"rowId": "3",
"colName": "Category Name",
"colId": "A",
"value": "Condiments"
},
"4": {
"rowName": "",
"rowId": "3",
"colName": "Quantity",
"colId": "B",
"value": "378"
},
"5": {
"rowName": "",
"rowId": "3",
"colName": "Amount",
"colId": "C",
"value": "$107"
},
"6": {
"rowName": "",
"rowId": "4",
"colName": "Category Name",
"colId": "A",
"value": "Confections"
},
"7": {
"rowName": "",
"rowId": "4",
"colName": "Amount",
"colId": "C",
"value": "$22877"
}
}
}
I need to display the values in a html table using js/jquery like
A B C
--|-----------|-------- |-------------|-
2|Beverages | 925 | $277 |
3|Condiments | 378 | $107 |
4|Confections| -- | $22877 |
| | | |
The JSON also may contain the null values. The fields are displayed with respect to rowId and colId. The table values are displayed in JSON field 'value'.
ONE METHOD:
http://www.json.org/
Use the above link and grab the function for handling JSON response and include in you js file
/*setting the var to hold the json array*/
var jsonReturn = xmlhttp.responseText;
/*parse the JSON data using the JSON function from the JSON website*/
var jsonReturn = json_parse(jsonReturn);
/*now you can access all the data in the typical javascript array format... eg:*/
var returnedID = jsonReturn.id;
var userId = jsonReturn.userId;
/*repeat the above to get all the data you need*/
/*.......
........*/
/*now you can loop through the data array*/
for(var x=0; x < jsonReturn.data.length; x++)
{
var rowName = jsonReturn.data[x].rowName;
var rowId= jsonReturn.data[x].rowId;
var colName= jsonReturn.data[x].colName;
var colId= jsonReturn.data[x].colId;
var value= jsonReturn.data[x].value;
/** now you have all the data you need from the JSON response you can bever away and generate the table **/
}
SlickGrid will allow you to do that. You may have to convert the data model slightly for what it expects, but SlickGrid has a model system that allows for this (one of the more advanced examples being in the RemoteModel, for data retrieved via AJAX).
(Strictly speaking, you don't get an HTML <table/> out of it, but a number of <div/> elements.)
I use
http://datatables.net/usage/
which is simpler, or
http://www.trirand.com/blog/
that has more features .

Categories

Resources