I have 2 json files, or String and i want to merge them based on ID. Like join on sql. This is the example:
This is Json 1:
{
"City": [{
"CityId": 9,
"CityName": "Kukes"
}, {
"CityId": 18,
"CityName": "Tirana"
}, {
"CityId": 19,
"CityName": "Vlore"
}, {
"CityId": 22,
"CityName": "temp"
}]
}
And this i json 2:
{
"Citizen": [{
"CitizenId": 38,
"CitizenLastName": "Bale",
"CitizenName": "Christian",
"City_Id": 19
}, {
"CitizenId": 39,
"CitizenLastName": "ttrtrt",
"CitizenName": "test",
"City_Id": 18
}, {
"CitizenId": 42,
"CitizenLastName": "Freeman",
"CitizenName": "Morgan",
"City_Id": 9
}, {
"CitizenId": 43,
"CitizenLastName": "Snow",
"CitizenName": "Jon",
"City_Id": 9
}, {
"CitizenId": 44,
"CitizenLastName": "test2",
"CitizenName": "test",
"City_Id": 9
}]
}
I want it to merge in a json file or string based on id like this structure:
{
"City":
[
{
"CityId":9,
"CityName":"Kukes",
"Citizens" : [{"CitizenId":42,"CitizenLastName":"Freeman","CitizenName":"Morgan","City_Id":9},{"CitizenId":43,"CitizenLastName":"Snow","CitizenName":"Jon","City_Id":9},{"CitizenId":44,"CitizenLastName":"test2","CitizenName":"test","City_Id":9}]
},
{
"CityId":18,
"CityName":"Tirana",
"Citizens" : [{"CitizenId":39,"CitizenLastName":"ttrtrt","CitizenName":"test","City_Id":18}]
},
{
"CityId":19,
"CityName":"Vlore",
"Citizens" : [{"CitizenId":38,"CitizenLastName":"Bale","CitizenName":"Christian","City_Id":19}]
},
{
"CityId":22,
"CityName":"temp",
"Citizens" : []
}
]
}
I've tried all day and still found nothing. Do you have any idea how to do this with Newtonsoft? Or any other way? But I'd like it with newtonsoft.
You can do this with LINQ to JSON, using ToLookup() to find all citizens for a given city:
var cities = JToken.Parse(cityJson);
var citizens = JToken.Parse(citizenJson);
var lookup = citizens.SelectTokens("Citizen[*]").ToLookup(c => (string)c["City_Id"]);
foreach (var city in cities.SelectTokens("City[*]"))
{
city["Citizens"] = new JArray(lookup[(string)city["CityId"]]);
}
Prototype fiddle.
To load your JSON from a file, then later save back, see Read JSON from a file and Write JSON to a file.
Related
I have a json file like this:
[
{
"key1": {
"find": 5,
"count": 65,
"name": "Parser"
},
"init": {
"key2": {
"find": 5,
"count": 15,
"name": "Some"
},
"arr": [
{
"key2": {
"find": 8,
"count": 32,
"name": "Object"
},
"temp": {
"pay": null
}
}
]
}
},
{
"key3": {
"find": 5,
"count": 23,
"name": "String"
},
"classes": [],
}
]
And I want to get list of all nodes that contains key "find" and value "5". The result have to be:
{
"find": 5,
"count": 65,
"name": "Parser"
},
{
"find": 5,
"count": 15,
"name": "Some"
},
{
"find": 5,
"count": 23,
"name": "String"
}
The difficulty is that the nesting can be any, but I need to get only those nodes that contain key "find" and the value "5" for it. How can I go through the entire file and get the nodes I need?
You can use JToken for this purpose, use the below function to find the nodes.
public void FindNodes(JToken json, string name, string value, List<JToken> nodes)
{
if (json.Type == JTokenType.Object)
{
foreach (JProperty child in json.Children<JProperty>())
{
if (child.Name == name && child.Value.ToString() == value)
{
nodes.Add(child);
}
FindNodes(child.Value, name, value, nodes);
}
}
else if (json.Type == JTokenType.Array)
{
foreach (JToken child in json.Children())
{
FindNodes(child, name, value, nodes);
}
}
}
Use the method in this way,
var json = JsonConvert.DeserializeObject<JToken>(jsonString);
var nodes = new List<JToken>();
FindNodes(json, "find", "5", nodes);
I have two JSON objects -
json1 = {
"payload": {
"firstName": "John",
"lastName": "Doe",
"code": "test1",
"arrayProp1": [1, 2, 3],
"arrayProp2": [{
"prop1": "value1",
"prop2": "value2"
},
{
"prop1": "2_value1",
"prop2": "2_value2"
}
]
}
}
json2 = {
"payload": {
"code": "newCode",
"arrayProp1": [3,4],
"arrayProp2": [{
"prop1": "newValue1",
"prop2": "newValue2"
}
]
}
}
If I use the built-in merge (json1.Merge(json2)) the result obtained is -
result : {
"payload": {
"firstName": "John",
"lastName": "Doe",
"code": "newCode",
"arrayProp1": [1, 2, 3, 3, 4],
"arrayProp2": [{
"prop1": "value1",
"prop2": "value2"
},
{
"prop1": "newValue1",
"prop2": "newValue2"
},
{
"prop1": "2_value1",
"prop2": "2_value2"
}
]
}
}
Expected result -
{
"payload": {
"firstName": "John",
"lastName": "Doe",
"code": "newCode",
"arrayProp1": [3, 4],
"arrayProp2": [{
"prop1": "newValue1",
"prop2": "newValue2"
}]
}
}
I want to replace the parent property values of json1 based on values provided in json2.
I tried to write a function and this is the current version I have -
string Merge(string req1, string req2) {
try
{
JObject json1 = JObject.Parse(req1);
JObject json2 = JObject.Parse(req2);
foreach (var a in json2.DescendantsAndSelf())
{
if (a is JObject obj)
{
foreach (var prop in obj.Properties())
{
if(json1.SelectTokens(prop.Path).Any())
{
json1[prop.Path] = prop.Value;
}
}
}
}
req1 = json1.ToString();
}
catch(Exception ex)
{
//do nothing
}
return req1; }
There are 2 problems here -
"payload" is identified as property and json1 is replaced fully by json2 because of which I lose some of its properties.
After being replaced, when the loop continues to run, say property 'code' is to be updated, then the property path is payload.code, so on the line json1[prop.path] = prop.Value, instead of updating the existing code in the payload, it creates a new property called payload.code with value "newcode"
The final result of the code above is -
{
"payload": {
"code": "newCode",
"arrayProp1": [3, 4],
"arrayProp2": [{
"prop1": "newValue1",
"prop2": "newValue2"
}],
"payload.code": "newCode",
"payload.arrayProp1": [3, 4],
"payload.arrayProp2": [{
"prop1": "newValue1",
"prop2": "newValue2"
}],
"payload.arrayProp1[0].prop1": "newValue1",
"payload.arrayProp1[0].prop2": "newValue2"
}
}
Can someone please help me with this?
Your requirement is that array contents are replaced rather than concatenated when merging two JSON objects with JContainer.Merge(). You can achieve this via the JsonMergeSettings.MergeArrayHandling setting, which has the following values:
Concat 0 Concatenate arrays.
Union 1 Union arrays, skipping items that already exist.
Replace 2 Replace all array items.
Merge 3 Merge array items together, matched by index.
Specifically MergeArrayHandling.Replace will work as required:
json1.Merge(json2, new JsonMergeSettings
{
MergeArrayHandling = MergeArrayHandling.Replace
});
Demo fiddle here.
Consider you have Order and OrderDetails. I'm trying to filter order details for the specific order.
For instance if you have document something like this:
{
"orders": [
{
"id": 1,
"date": "02.04.2020 ...",
"user": {
"name": "xx",
"surname": "yy"
},
"orderDetails": [
{
"id": 1,
"productId": 5,
"quantity": 1,
"state": 3
},
{
"id": 2,
"productId": 3,
"quantity": 4,
"state": 3
},
{
"id": 3,
"productId": 4,
"quantity": 12,
"state": 2
},
{
"id": 4,
"productId": 7,
"quantity": 8,
"state": 2
},
{
"id": 5,
"productId": 12,
"quantity": 9,
"state": 3
}
]
},
{
"id": 2,
"date": "01.04.2020 ...",
"user": {
"name": "xx",
"surname": "yy"
},
"orderDetails": [
{
"id": 6,
"productId": 5,
"quantity": 1,
"state": 3
},
{
"id": 7,
"productId": 3,
"quantity": 4,
"state": 3
},
{
"id": 8,
"productId": 4,
"quantity": 12,
"state": 2
}
]
}
}
What I'm trying to do is first filtering by order and then state of an order detail. I have a code like this but it always brings correct order with all orderDetails. Seems like it doesn't care about equal filter for orderDetails.
Actually it's working but not filtering. Because I only have 3 types of state(enum) and int values are 1,2,3. Query brings nothing if I give 4.
var builder = Builders<Order>.Filter;
var filter = builderk.And(builder.Eq("_id", ObjectId.Parse(elementid)), builder.Eq("orderDetails.state", 3));
var result = _mongoRepository.FindByFilter(filter).ToList();
I also tried AnyEq and something like that filters but didn't work.
I will be very happy if anyone can help me.
Thanks.
You can use aggregation operation for operations such as filter sorting in detail records.
If we continue through the sample, you must first create a filter for your master data.
var builderMaster = Builders<Order>.Filter;
var filterMaster = builderMaster.Eq("_id", ObjectId.Parse(elementid));
Then you need to create a different filter for the details.
Important: You must use the BsonDocument type when creating detail filters. Because you cannot give a specific type when you filter the details.
var builderDetail = Builders<BsonDocument>.Filter;
var filterDetail = builderDetail.Eq("orderDetails.state", 3);
Then you can start typing the query.
var list = _mongoRepository.Aggregate()
.Match(filterMaster)
.Unwind("orderDetails")// Name the details.
.Match(filterDetail)
.Sort(sort)// optionally
.Skip(skip) // optionally
.Limit(limit) // optionally
.ToList();
It will give you a list of BsonDocument with the given parameters. After that, you have to map with your own detail class.
var resultList = new List<OrderDetails>();
foreach (var master in list)
{
var masterObj = BsonSerializer.Deserialize<dynamic>(master);
foreach (var item in masterObj)
{
if (item.Key == "orderDetails")
{
var mapper = new MapperConfiguration(cfg => { }).CreateMapper();
var retItem = mapper.Map<OrderDetails>(item.Value);
resultList.Add(retItem);
}
}
}
Hi so I have 2 Table with one to many Relationship, I use ado net and Join query to get the Table and the referenced one, after that I cast my DataTable as Enumerable and then use the Linq operation to return it as nested JSON. But the problem is only the GroupBy field will return one data using the key and every else will return an array as many as the record have like this
{
"id": 23,
"date": [
"2018-01-01T00:00:00",
"2018-01-01T00:00:00",
"2018-01-01T00:00:00",
"2018-01-01T00:00:00"
],
"total_room_sold": [
41,
41,
41,
41
],
"total_rom_revenue": [
19340082,
19340082,
19340082,
19340082
],
"Segment": {
"segment_name": [
"BFR",
"DIS",
"PAR",
"LON"
],
"room_sold": [
4,
2,
1,
0
],
"revenue_by_segment": [
1904628,
686605,
461157,
0
]
}
}
And for the N:1 Table do I need to GroupBy again so I can get like this for the segment
{
"id": 23,
"date": [
"2018-01-01T00:00:00",
"2018-01-01T00:00:00",
"2018-01-01T00:00:00",
"2018-01-01T00:00:00"
],
"total_room_sold": [
41,
41,
41,
41
],
"total_rom_revenue": [
19340082,
19340082,
19340082,
19340082
],
"Segment": [
{
"segment_name": "BFR",
"rooom_sold" : 4,
"revenue_by_segment" : 412313213
},
{
"segment_name": "BFR",
"rooom_sold" : 2,
"revenue_by_segment" : 12312313
}
]
}
My code for now
var dt = dt.AsEnumerable().GroupBy(x => x.Field<dynamic>(id)).Select(x => new {
id = x.key,
date = x.Field<dynamic>("date"),
total_room_sold = x.Field<dynami>(total_room_sold),
Segment = x.Select(s => new {
segment_name = s.Field<dynamic>("segment_name"),
room_sold = s.Field<dynamic>("room_sold"),
})
})
I have a JSON object as below
[
{
"Id": 7,
"Name": "Colocation Folder",
"ParentId": 1,
"depth": 0
},
{
"Id": 8,
"Name": "CoLo Real Estate",
"ParentId": 7,
"depth": 1
},
{
"Id": 10,
"Name": "CoLo: Burst",
"ParentId": 7,
"depth": 1
},
{
"Id": 34,
"Name": "CoLo Dedicated Bandwidth",
"ParentId": 7,
"depth": 1
},
{
"Id": 10035,
"Name": "Infrastructure as a Service",
"ParentId": 7,
"depth": 1
},
{
"Id": 10037,
"Name": "Software as a Service",
"ParentId": 7,
"depth": 1
},
{
"Id": 10038,
"Name": "IaaS Component Upgrade",
"ParentId": 7,
"depth": 1
},
{
"Id": 668,
"Name": "CoLo Misc Folder",
"ParentId": 7,
"depth": 1
},
{
"Id": 758,
"Name": "CoLo: Conduit Fee",
"ParentId": 668,
"depth": 2
},
{
"Id": 765,
"Name": "CoLo: Private VLAN",
"ParentId": 668,
"depth": 2
}
]
The Id and ParentId fields show the relation between the items. I need to make it as a nested JSON using C#.
Since there will be many such models, I don't want to create individual classes for each model. Is there a generic approach in C# that will take a flat JSON array, take the ID and ParentId fields as input and then return me a nested JSON with all other fields in the array as well? For example, I am looking for an output of nested JSON as below:
[
{
"Id": 7,
"Name": "Colocation Folder",
"items": [
{
"Id": 8,
"Name": "CoLo Real Estate",
"ParentId": 7
},
{
"Id": 10,
"Name": "CoLo: Burst",
"ParentId": 7
},
{
"Id": 34,
"Name": "CoLo Dedicated Bandwidth",
"ParentId": 7
},
{
"Id": 10035,
"Name": "Infrastructure as a Service",
"ParentId": 7
},
{
"Id": 10037,
"Name": "Software as a Service",
"ParentId": 7
},
{
"Id": 10038,
"Name": "IaaS Component Upgrade",
"ParentId": 7
},
{
"Id": 668,
"Name": "CoLo Misc Folder",
"ParentId": 7,
"items": [
{
"Id": 758,
"Name": "CoLo: Conduit Fee",
"ParentId": 668
},
{
"Id": 765,
"Name": "CoLo: Private VLAN",
"ParentId": 668
}
]
}
]
}
]
If you use Json.Net, you can do this conversion in a generic way using the LINQ-to-JSON API (JObjects). The idea is to parse the JSON array and add all the individual items to a dictionary keyed by Id. Then, loop over the dictionary items, and for each one, try to look up the parent. If the parent is found, add the item to the parent's items array (creating it if needed). Otherwise, add the item to the root array. Along the way, remove the depth property from each item, since you don't seem to want that in the output. Lastly, just dump the root array to string to get the final result.
var dict = JArray.Parse(json)
.Children<JObject>()
.ToDictionary(jo => (string)jo["Id"], jo => new JObject(jo));
var root = new JArray();
foreach (JObject obj in dict.Values)
{
JObject parent;
string parentId = (string)obj["ParentId"];
if (parentId != null && dict.TryGetValue(parentId, out parent))
{
JArray items = (JArray)parent["items"];
if (items == null)
{
items = new JArray();
parent.Add("items", items);
}
items.Add(obj);
}
else
{
root.Add(obj);
}
JProperty depth = obj.Property("depth");
if (depth != null) depth.Remove();
}
Console.WriteLine(root.ToString());
Fiddle: https://dotnetfiddle.net/Buza6T
You can use a dynamic object with JSON.Net like so to detect your properties dynamically then you could build a new json object with the desired nesting:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
dynamic d = JArray.Parse(stringy);
foreach(var ob in d)
{
if(ob.ParentID != ob.Id)
{
string debug = "oh snapple, it's a child object";
}
}
Share my working code for you at jsFiddle full source code
recursive function is:
function getNestedChildren(arr, parent) {
var out = []
for(var i in arr) {
if(arr[i].parent == parent) {
var children = getNestedChildren(arr, arr[i].id)
if(children.length) {
arr[i].children = children
}
out.push(arr[i])
}
}
return out
}
full source code:
function getNestedChildren(arr, parent) {
var out = []
for(var i in arr) {
if(arr[i].ParentId == parent) {
var items = getNestedChildren(arr, arr[i].Id)
if(items.length) {
arr[i].items = items
}
out.push(arr[i])
}
}
return out
}
var flat_array = [
{
"Id": 7,
"Name": "Colocation Folder",
"ParentId": 1,
"depth": 0
},
{
"Id": 8,
"Name": "CoLo Real Estate",
"ParentId": 7,
"depth": 1
},
{
"Id": 10,
"Name": "CoLo: Burst",
"ParentId": 7,
"depth": 1
},
{
"Id": 34,
"Name": "CoLo Dedicated Bandwidth",
"ParentId": 7,
"depth": 1
},
{
"Id": 10035,
"Name": "Infrastructure as a Service",
"ParentId": 7,
"depth": 1
},
{
"Id": 10037,
"Name": "Software as a Service",
"ParentId": 7,
"depth": 1
},
{
"Id": 10038,
"Name": "IaaS Component Upgrade",
"ParentId": 7,
"depth": 1
},
{
"Id": 668,
"Name": "CoLo Misc Folder",
"ParentId": 7,
"depth": 1
},
{
"Id": 758,
"Name": "CoLo: Conduit Fee",
"ParentId": 668,
"depth": 2
},
{
"Id": 765,
"Name": "CoLo: Private VLAN",
"ParentId": 668,
"depth": 2
}
]
var nested = getNestedChildren(flat_array, 1)
console.log(nested)