I have JSON :
[
{
"Position": "ProjectManager",
"Salary": 2000
},
{
"Position": "BusinessAnalyst",
"Salary": 2001
},
{
"Position": "TechnicalLead",
"Salary": 2002
},
{
"Position": "SeniorSoftwareEngineer",
"Salary": 2003
},
{
"Position": "SoftwareEngineer",
"Salary": 2004
},
{
"Position": "JuniorSoftwareEngineer",
"Salary": 2005
},
{
"Position": "UIUXEngineer",
"Salary": 2006
},
{
"Position": "QALead",
"Salary": 2007
},
{
"Position": "SeniorQAEngineer",
"Salary": 2008
},
{
"Position": "QAEngineer",
"Salary": 2009
},
{
"Position": "JuniorQAEngineer",
"Salary": 2010
},
{
"Position": "SeniorAutomationEngineer",
"Salary": 2011
},
{
"Position": "AutomationEngineer",
"Salary": 2012
},
{
"Position": "JuniorAutomationEngineer",
"Salary": 2013
}
]
But I need to convert it into this example :
{
"ProjectManager": "2000",
"BusinessAnalyst": "2001",
"TechnicalLead": "2002",
"SeniorSoftwareEngineer": "2003",
"SoftwareEngineer": "2004",
"JuniorSoftwareEngineer": "2005",
"UIUXEngineer": "2006",
"QALead": "2007",
"SeniorQAEngineer": "2008",
"QAEngineer": "2009",
"JuniorQAEngineer": "2010",
"SeniorAutomationEngineer": "2011",
"AutomationEngineer": "2012",
"JuniorAutomationEngineer": "2013"
}
As you see in 2nd example i have just values and no properties. How can i do this? (Currentrly my idea is to parse Json as string and remove all tokens that match "Position :" or "Salary :")
You dont need to doo so much a stuff.
I can metioned a method.
let your json one is probjson and result asresjson
var arr=new [];
var res=new { arr }
for(var i in probjson.length){
var position=probjson[i].Position;
var salary=probjson[i].Salary;
var v = new { position=salary }
res.arr.add(V);
}
this not a complete one
plz try to get a idea.
thankz
One approach would be iterating each object in the array and populate a dictionary:
// Using JSON.NET you can deserialize the JSON array as an enumerable
// of dynamically-typed objects (i.e. your array)
IEnumerable<dynamic> employees = JsonConvert
.DeserializeObject<IEnumerable<dynamic>>
(
jsonText
);
Dictionary<string, object> values = new Dictionary<string, object>();
foreach(dynamic employee in employees)
{
values.Add((string)employee.Position, (object)employee.Salary);
}
// .NET dictionaries are deserialized into JSON objects!
string convertedJson = JsonConvert.SerializeObject(values);
Check a working sample on .NET Fiddle!
Update
And if you want a one-liner LINQ extension methods-based solution, what about:
string convertedJson = JsonConvert.SerializeObject
(
JsonConvert.DeserializeObject<IEnumerable<dynamic>>(jsonText)
.ToDictionary(employee => employee.Position, employee => employee.Salary)
);
Related
I have such items in Dynamo DB:
[{
"Id": "1",
"Data": {
"Value": "test"
}
},
{
"Id": "2",
"Data": {}
},
{
"Id": "3"
},
{
"Id": "4",
"Data": {
"Wrong": "234"
}
}]
And I'm trying to make it flatten, but for the Data.Value field only:
[{
"Id": "1",
"Value": "test"
},
{
"Id": "2"
},
{
"Id": "3"
},
{
"Id": "4"
}]
My Update request looks like this:
var request = new UpdateItemRequest {
TableName = "<table>",
Key = new Dictionary<string, AttributeValue> {{"Id", new AttributeValue("<item-id>")}},
UpdateExpression = "SET #a = #c.#a REMOVE #c",
ExpressionAttributeNames = new Dictionary<string, string> {
{"#c", "Data"},
{"#a", "Value"}
}
};
This works well for Id = 1 and 3. But does not work for 2 and 4. I assume because it can not do a SET. It does not throw any errors, but simply does not delete the Data attribute.
Is there a way to make it in a single call?
you just need a condition with your expression, to check if the attribute exist or not, thats it.
ConditionExpression ="attribute_exists (#c.#a)"
For more détails in Amazon doncs here.
I am working with an API that uses GraphQL and returns JSON data and I want to deserialize the JSON content dynamically rather than map the entire service structure in my application into C# data structures (.NET types/classes).
I've done this before but the JSON data was quite simple and straightforward. However, the this API I'm working with returns more complex/verbose JSON and I'm struggling to parse it properly.
Can anyone advise on how to parse the below JSON? That is, how to access the dynamic JSON's objects/properties.
I'm using Newtonsoft.Json. This is my code to deserialize:
byte bC = 0;
string location_text = string.Empty;
string location_value = string.Empty;
dynamic results = JsonConvert.DeserializeObject<dynamic>(json);
foreach (dynamic d in results)
{
bC = d.data.locationSuggestions.Count; // d.locationSuggestions.Count
for (byte b = 0; b < bC; b++)
{
location_text = d.data.locationSuggestions[b].location.contextualName;
location_value = d.data.locationSuggestions[b].location.id.value;
}
}
When I run this code I get an error that says "data" or "locationSuggestions" cannot be found.
The JSON I'm trying to parse is as follows:
{
"data": {
"locationSuggestions": [
{
"location": {
"id": {
"value": "seekAnzPublicTest:location:seek:2dkY4vZJF"
},
"name": "Brisbane",
"contextualName": "Brisbane QLD 4000 AU",
"countryCode": "AU",
"parent": {
"id": {
"value": "seekAnzPublicTest:location:seek:2FjxhQans"
},
"name": "CBD & Inner Suburbs",
"parent": {
"id": {
"value": "seekAnzPublicTest:location:seek:32XZdsa2K"
},
"name": "Brisbane"
}
}
}
},
{
"location": {
"id": {
"value": "seekAnzPublicTest:location:seek:2ckmimaF1"
},
"name": "Brisbane Grove",
"contextualName": "Brisbane Grove NSW 2580 AU",
"countryCode": "AU",
"parent": {
"id": {
"value": "seekAnzPublicTest:location:seek:2UC23LszP"
},
"name": "Southern Highlands & Tablelands",
"parent": {
"id": {
"value": "seekAnzPublicTest:location:seek:FTwZdE2K"
},
"name": "New South Wales"
}
}
}
}
]
},
"extensions": {
"requestLatency": 171
}
}
Regarding your JSON string, you can use dynamic to parse it and access the data as shown below:
You can also find a working example at: https://dotnetfiddle.net/lnhwJz
using System;
using Newtonsoft.Json;
public class Program
{
public static void Main()
{
var jsonString=#"{'data':{'locationSuggestions':[{'location':{'id':{'value':'seekAnzPublicTest:location:seek:2dkY4vZJF'},'name':'Brisbane','contextualName':'Brisbane QLD 4000 AU','countryCode':'AU','parent':{'id':{'value':'seekAnzPublicTest:location:seek:2FjxhQans'},'name':'CBD & Inner Suburbs','parent':{'id':{'value':'seekAnzPublicTest:location:seek:32XZdsa2K'},'name':'Brisbane'}}}},{'location':{'id':{'value':'seekAnzPublicTest:location:seek:2ckmimaF1'},'name':'Brisbane Grove','contextualName':'Brisbane Grove NSW 2580 AU','countryCode':'AU','parent':{'id':{'value':'seekAnzPublicTest:location:seek:2UC23LszP'},'name':'Southern Highlands & Tablelands','parent':{'id':{'value':'seekAnzPublicTest:location:seek:FTwZdE2K'},'name':'New South Wales'}}}}]},'extensions':{'requestLatency':171}}";
var parsedData=JsonConvert.DeserializeObject<dynamic>(jsonString);
foreach(var item in parsedData.data.locationSuggestions)
{
Console.WriteLine(item.location.name);
Console.WriteLine(item.location.id.value);
Console.WriteLine(item.location.contextualName);
}
}
}
Output:
Brisbane
seekAnzPublicTest:location:seek:2dkY4vZJF
Brisbane QLD 4000 AU
Brisbane Grove
seekAnzPublicTest:location:seek:2ckmimaF1
Brisbane Grove NSW 2580 AU
For example I have a document below for collection = delivery:
{
"doc": [
{
"docid": "15",
"deliverynum": "123",
"text": "txxxxxx",
"date": "2019-07-18T12:37:58Z"
},
{
"docid": "16",
"deliverynum": "456",
"text": "txxxxxx",
"date": "2019-07-18T12:37:58Z"
},
{
"docid": "17",
"deliverynum": "999",
"text": "txxxxxx",
"date": "2019-07-18T12:37:58Z"
}
],
"id": "123",
"cancelled": false
}
is it possible to do a search with "deliverynum" = 999 and the output would be like below?
{
"doc": [
{
"docid": "17",
"deliverynum": "999",
"text": "txxxxxx",
"date": "2019-07-18T12:37:58Z"
}
],
"id": "123",
"cancelled": false
}
or should I make another Collection just for the Doc part?
I am having trouble making a query in C# for this kind of scenario.
In Mongo shell you can use the $(projection) operator:
db.collection.find({ "doc.deliverynum": "999" }, { "doc.$": 1 })
Corresponding C# code can look like below:
var q = Builders<Model>.Filter.ElemMatch(x => x.doc, d => d.deliverynum == "999");
var p = Builders<Model>.Projection.ElemMatch(x => x.doc, d => d.deliverynum == "999");
var data = Col.Find(q).Project(p).ToList();
You can also use q = Builders<Model>.Filter.Empty if you want to get all documents even if the don't contain deliverynum =``999
I have a json response with multiple movie titles in "data". Is there a way to quickly extract them? I need an array with just movie titles.
{
"page": "2",
"per_page": 10,
"total": 13,
"total_pages": 2,
"data": [{
"Poster": "N/A",
"Title": "They Call Me Spiderman",
"Type": "movie",
"Year": 2016,
"imdbID": "tt5861236"
}, {
"Poster": "N/A",
"Title": "The Death of Spiderman",
"Type": "movie",
"Year": 2015,
"imdbID": "tt5921428"
}, {
"Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BZDlmMGQwYmItNTNmOS00OTNkLTkxNTYtNDM3ZWVlMWUyZDIzXkEyXkFqcGdeQXVyMTA5Mzk5Mw##._V1_SX300.jpg",
"Title": "Spiderman in Cannes",
"Type": "movie",
"Year": 2016,
"imdbID": "tt5978586"
}]
}
You can use:
newtonsoft.
C# System.dynamic.
C# ExpandoObject Class.
In this way:
dynamic content = JsonConvert.DeserializeObject<ExpandoObject>(data);
Something like this:
using System;
using System.Dynamic;
using Newtonsoft.Json;
public class Program
{
public static void Main()
{
string data = #"{
'page': '2',
'per_page': 10,
'total': 13,
'total_pages': 2,
'data': [{
'Poster': 'N/A',
'Title': 'They Call Me Spiderman',
'Type': 'movie',
'Year': 2016,
'imdbID': 'tt5861236'
}, {
'Poster': 'N/A',
'Title': 'The Death of Spiderman',
'Type': 'movie',
'Year': 2015,
'imdbID': 'tt5921428'
}, {
'Poster': 'https://images-na.ssl-images-amazon.com/images/M/MV5BZDlmMGQwYmItNTNmOS00OTNkLTkxNTYtNDM3ZWVlMWUyZDIzXkEyXkFqcGdeQXVyMTA5Mzk5Mw##._V1_SX300.jpg',
'Title': 'Spiderman in Cannes',
'Type': 'movie',
'Year': 2016,
'imdbID': 'tt5978586'
}]
}";
dynamic content = JsonConvert.DeserializeObject<ExpandoObject>(data);
int i;
int len = content.data.Count;
string result = "";
string[] myArray;
for (i = 0; i < len; i++)
{
result += content.data[i].Title; // Extract the movie title.
result += ","; // Conact with commas.
}
result = result.Substring(0, result.Length - 1);
myArray = result.Split(','); // Array of string with the movie titles.
Console.WriteLine(myArray[0]);
}
}
See in action: .NET Fiddle.
var data = new Dictionary<string, string>();
data.Add("foo", "baa");
JavaScriptSerializer ser = new JavaScriptSerializer();
var JSONString = ser.Serialize(data); //JSON encoded
var JSONObj = ser.Deserialize<Dictionary<string, string>>(JSONString); //JSON decoded
Console.Write(JSONObj["foo"]); //prints: baa
using Newtonsoft.Json.Linq might do the simplest work for you.
using Newtonsoft.Json.Linq;
List<string> movieTitles = (JObject.Parse(json)["data"]).
Cast<JToken>().Select(x => x["Title"].ToString()).ToList();
The following code:
var data = _context.People.ToList(); //_context is my DataContext.
produces the result:
[{ "name": "john", "age": "30" }, { "name": "jane", "age": "31" }]
but, I want it to be a dictionary, so something like:
{ "xldata" : [{ "name": "john", "age": "30" }, { "name": "jane", "age": "31" }] }
I got it to work by doing:
Dictionary<string,List<People>> vals = new Dictionary<string, List<People>>();
vals.Add("xldata", people);
but, my dictionary's value is System.Object[] instead of the people
The purpose of this is to export data, so when I get to this line:
var people = jss.Deserialize<List<People>>(args["xldata"]);
args["xldata"] is `System.Object[]` and it says `Invalid JSON primitive`.
Here is the script is supposed to export the data to excel:
$.post(urlContent + exportHandlerPath, Json, function(data) {
var viewData = {};
viewData.xldata = JSON.stringify(data);
html = ich.excelExportTemplate(viewData);
$excelExportContainer.html(html);
var input = $excelExportContainer.find('input#excelExportHiddenField');
input.val(viewData.xldata);
var $excelForm = $('#excelExportForm');
$excelForm.attr('action', '/People/ExportToExcel/');
$excelForm.submit();
}
Apparently your args["xldata"] does not contain a json string like [{ "name": "john", "age": "30" }, { "name": "jane", "age": "31" }], but something returned by a .net object .ToString().
With JavaScriptSerializer.Deserialize you can only deserialize json represenations.