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 .
Related
I'm trying to get the title of the first song in the JSON Object below but I have to go through a number as a key name.
Normally, we can do like this: title = top100.content.rank.title but it doesn't work with title = top100.content.1.title like the Object below.
My current solution is: title = Object.values(Object.values(top10.data)[1])[0].title which is very long and ugly. If you have a better way, please help me.
top100 = {
"info": {
"category": "Billboard",
"chart": "HOT 100",
"date": "2021-09-11",
"source": "Billboard-API"
},
"content": {
"1": {
"rank": "1",
"title": "Butter",
"artist": "BTS",
"weeks at no.1": "10",
"last week": "7",
"peak position": "1",
"weeks on chart": "15",
"detail": "up"
},
"2": {
"rank": "2",
"title": "Stay",
"artist": "The Kid LAROI & Justin Bieber",
"last week": "1",
"peak position": "1",
"weeks on chart": "8",
"detail": "down"
},
...
}
}
you can use the obj[key] syntax
top100['content'][1]['title']
you can access title of the first song in this way:
top100.content["1"].title
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.
I am trying to serialize a dictionary in C# using JSON.NET and then consume it in a web application. This is the format I am returned but am unable to use it as I do not think it is in the correct format. I have tried the following:
Dictionary Serialization:
[JsonExtensionData]
public static Dictionary<string, object> objectDictionary = new Dictionary<string, object>();
string parametersJSON = JsonConvert.SerializeObject(objectDictionary, Formatting.Indented);
var x = get.getData;
x.p11.Name
{
"p11": {
"Name": "Parameter 1",
"Value": "1.00",
"Unit": "m",
"MinValue": "0.00",
"MaxValue": "5.00",
"Number": 11,
"DefaultValue": "0.00"
},
"p546": {
"Name": "Parameter 2",
"Value": "0.0000",
"Unit": "Hz",
"MinValue": "-480.000",
"MaxValue": "480.000",
"Number": 546,
"DefaultValue": "0.0000"
},
"p7": {
"Name": "Parameter 3",
"Value": "0.00",
"Unit": "Amps",
"MinValue": "0.00",
"MaxValue": "44.00",
"Number": 7,
"DefaultValue": "0.00"
}}
Nothing is wrong with your data:
var x = JSON.parse(jsonstr);
var name = x["p11"].Name;
For more information:
A Dictionary is parsed into an associative array (http://www.w3schools.com/js/js_arrays.asp)
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.
How can I append a text to only the first value of an array and send the array back to the server. This is the response i am getting from the server
[{
"12": [ "12", "1", "2", "3" ]
}, {
"13": [ "13", "1", "2", "3" ]
}, {
"14": [ "14", "1", "2", "3" ]
}, {
"15": [ "15", "1", "2", "3" ]
}]
I want my array to now be like this so that i can pass this array to my data table.
var object = [{
12: ["12 hrs", "1", "2", "3"]
}, {
13: ["13 hrs", "1", "2", "3"]
}, {
14: ["14 hrs", "1", "2", "3"]
}, {
15: ["15 hrs", "1", "2", "3"]
}]
How can I append hrs to the first value?
Here's one easy method...
// Parse the string response from the server into an object
var obj = JSON.parse(serverResponse);
// loop through the object, knowing that it's nested in the first index of an array "obj[0]"
for(id in obj[0]){
// obj->arrayIndex->objectProperty->arrayIndex append " hrs"
obj[0][id][0] += " hrs";
}
// to return this to the server, apply JSON.stringify(obj)
I fixed object in your question to -
var objectArray = [{"12" : ["12", "1", "2", "3"]}, {"13" : ["13", "1", "2", "3"]},{"14" : ["14", "1", "2", "3"]},{"15" : ["15", "1", "2", "3"]}]
This is how you can loop through the objectArray and change in the way you wanted -
for(var i=0;i<objectArray.length;i++)
{
for(var key in objectArray[i])
{
objectArray[i][key][0]+=" hrs";
break;
}
}
console.log(objectArray)