C# Serialize Dictionary JSON - javascript

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)

Related

JSON is valid but not working when sent to Xero

I have the below JSON which has been validated with https://jsonlint.com/. However, when I run this through Xero API, it throws an error, shown below.
{
"Type": "ACCREC",
"Status": "AUTHORISED",
"DueDate": "2021-12-11T14:24:08Z",
"InvoiceNumber": "PRO152125",
"Contact": {
"ContactID": "ddd-05f9-46dd-b4a6-2ccbb5deb330"
},
"LineItems": [
"{\"Description\": \"test1\", \"Qty\": 0.30, \"UnitAmount\": 950.0, \"TaxType\": \"OUTPUT2\", \"AccountCode\": \"200\"},\n{\"Description\": \"test2\", \"Qty\": 0.30, \"UnitAmount\": 300.0, \"TaxType\": \"OUTPUT2\", \"AccountCode\": \"200\"}"
]
}
{
"ErrorNumber": 14,
"Type": "PostDataInvalidException",
"Message": "JSON for post data was invalid,Error converting value \"{\"Description\": \"test1\", \"Qty\": 0.30, \"UnitAmount\": 950.0, \"TaxType\": \"OUTPUT2\", \"AccountCode\": \"200\"},\n{\"Description\": \"test2\", \"Qty\": 0.30, \"UnitAmount\": 300.0, \"TaxType\": \"OUTPUT2\", \"AccountCode\": \"200\"}\" to type 'Xero.API.Library.DataContracts.LineItem'. Path 'LineItems[0]', line 1, position 417."
}
Can anyone help with why this is happening?
API are trying to deserialize your json to the class like
class MyClass
{
..properties
List<LineItem> LineItems...
}
class LineItem
{
... properties inside of the string
}
your json is valid but it is
class MyClass
{
..properties
List<string> LineItems...
}
Api serializer can not convert List< string > to List< LineItem >. This is what causes the error
you can fix json this way
var jsonObject=GetFixedJsonObject(json);
var fixedJson=jsonObject.ToString();
public JObject GetFixedJsonObject(string json)
{
var jsonObject = JObject.Parse(json);
var jsonLineItems = "[" + (string)jsonObject["LineItems"][0] + "]";
jsonObject["LineItems"] = JArray.Parse(jsonLineItems);
return jsonObject;
}
fixed json
{
"Type": "ACCREC",
"Status": "AUTHORISED",
"DueDate": "2021-12-11T14:24:08Z",
"InvoiceNumber": "PRO152125",
"Contact": {
"ContactID": "ddd-05f9-46dd-b4a6-2ccbb5deb330"
},
"LineItems": [
{
"Description": "test1",
"Qty": 0.3,
"UnitAmount": 950.0,
"TaxType": "OUTPUT2",
"AccountCode": "200"
},
{
"Description": "test2",
"Qty": 0.3,
"UnitAmount": 300.0,
"TaxType": "OUTPUT2",
"AccountCode": "200"
}
]
}
You've got quotes around your line item, meaning it's just being seen as one big string. Try this:
{
"Type": "ACCREC",
"Status": "AUTHORISED",
"DueDate": "2021-12-11T14:24:08Z",
"InvoiceNumber": "PRO152125",
"Contact": {
"ContactID": "ddd-05f9-46dd-b4a6-2ccbb5deb330"
},
"LineItems": [{
"Description": "test1",
"Qty": 0.30,
"UnitAmount": 950.0,
"TaxType": "OUTPUT2",
"AccountCode": "200"
}, {
"Description": "test2",
"Qty": 0.30,
"UnitAmount": 300.0,
"TaxType": "OUTPUT2",
"AccountCode": "200"
}]
}

Fetch value based in that same JSON key value

I have the JSON like
var resultJSON = `{
"data": {
"total": 1,
"list_name": "title",
"title": {
"id": 53,
"name": "Sonu",
"mobileNo": "6543213456",
"address": "Greeny Pathway",
"city": "NewYork",
"mode": "Weekly",
"duration": "15",
"qty": null
},
"download": [{
"time": "16789042",
"date": "26 - 01 - 2020"
}]
}
}`;
I expect the output:
{
"total": "1",
"list_name": "title",
"name": "sonu",
"mobileno": "6543213456"
}
Here "list_name": "title" is dynamic, sometimes it will come "list_name": "book", based on that above mentioned response I want to get.
Something like this? I had to fix your invalid JSON
You can make it more clever if you study https://javascript.info/destructuring-assignment in depth
const resultJSON = `{
"data": {
"total": 1,
"list_name": "title",
"title": {
"id": 53,
"name": "Sonu",
"mobileNo": "6543213456",
"address": "Greeny Pathway",
"city": "NewYork",
"mode": "Weekly",
"duration": "15",
"qty": null
},
"download": [{
"time": "16789042",
"date": "26-01-2020"
}]
}
}`
const data = JSON.parse(resultJSON).data
const content = data[data.list_name];
let newObj = {}
newObj["total"] = data["total"];
newObj["list_name"] = data["list_name"];
newObj["name"] = content["name"];
newObj["mobileNo"] = content["mobileNo"];
console.log(newObj)

Change JSON format/layout

I have a universal variable on my website which includes line items with relevant details. These line items are reflective of what the user has in their cart. I am integrating with a third party who require the data passed through to them to be formatted slightly different. The below is the data layer currently on my website:
"lineItems": [
{
"product": {
"id": "s83y016b5",
"sku_code": "s83y016b5",
"url": "/en-gb/jeans/p/s83y016b5",
"image_url": "http://www.my-website.com/a/p/shirt.jpeg",
"name": "Jeans",
"manufacturer": "",
"category": "Everyday Wear",
"stock": 116,
"currency": "GBP",
"unit_sale_price": 16,
"unit_price": 16,
"size": "6-9 Months",
"color": "Indigo"
},
"quantity": 1
}
]
The below is what format the third party needs:
"lineItems": [
{
"sku": "s83y016b5",
"name": "Jeans",
"description": "A super great pair of jeans.",
"category": "Everyday Wear",
"other": {"fieldName": "This can be a string or any value you like"}
"unitPrice": 11.99,
"salePrice": 11.99,
"quantity": 2,
"totalPrice": 23.98
"imageUrl": "http://www.my-website.com/a/p/shirt.jpeg",
"productUrl": "http://www.my-website.com/index.php/shirt.html",
}]
Obviously this needs to be dynamic based on the products in the cart. What I intend to do is use javascript to amend the data and send this to the third party via Google Tag Manager.
Any help would be greatly appreciated. Any questions welcome.
This should be close to what you're looking for.
let oldLineItems = "your object";
let newLineItems = {};
newLineItems.lineItems = [];
for (let i in oldLineItems.lineItems) {
newLineItems.lineItems[i] = {};
for (let key in oldLineItems.lineItems[i].product)
{
newLineItems.lineItems[i][key] = oldLineItems.lineItems[i].product[key];
}
}
See code below.
I'm not sure how your lineItems object is set up, but below I just created an array called line Items. If line items is a key in an object which I suspect from your snippet above, you will have to go a level deeper in the for loops used in my example below.
Simply add further details to the new object in the nested for in loops below.
var lineItems =
[
{
"product": {
"id": "s83y016b5",
"sku_code": "s83y016b5",
"url": "/en-gb/jeans/p/s83y016b5",
"image_url": "http://www.my-website.com/a/p/shirt.jpeg",
"name": "Jeans",
"manufacturer": "",
"category": "Everyday Wear",
"stock": 116,
"currency": "GBP",
"unit_sale_price": 16,
"unit_price": 16,
"size": "6-9 Months",
"color": "Indigo",
"description": 'Some random description'
},
"quantity": 1
},
{
"product": {
"id": "s83y01699",
"sku_code": "s83y01699",
"url": "/en-gb/pants/p/s83y016b5",
"image_url": "http://www.my-website.com/a/p/pants.jpeg",
"name": "Pants",
"manufacturer": "",
"category": "Casual Wear",
"stock": 90,
"currency": "au",
"unit_sale_price": 14,
"unit_price": 14,
"size": "6-9 Months",
"color": "Indigo",
"description": 'Some random description'
},
"quantity": 14
},
];
var newLineItems = [];
for(var char in lineItems){
// Adding some values to newLineItems.
newLineItems.push({
sku: lineItems[char].product.sku_code,
name: lineItems[char].product.name,
description: lineItems[char].product.description,
category: lineItems[char].product.category,
quantity: lineItems[char].quantity
});
}
console.log(JSON.stringify(newLineItems));

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.

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