Access child token in JSON - json

In the below JSON I was trying to access the second array in the header.Basically "Node", "Percentage", "Time","File System" needs to captured as I will have to insert into SQL.My code is giving the complete array of header.
JObject jsonObject = JObject.Parse(jsonString);
List<string> childTokens = new List<string>();
foreach (var childToken in jsonObject.Children<JProperty>())
childTokens.Add(childToken.Name);
foreach (string childToken in childTokens)
{
if (jsonObject[childToken] is JObject)
{
JObject jObject = (JObject)jsonObject[childToken];
var jProperty = jObject.Children<JProperty>();
try
{
if (jProperty.LastOrDefault(x => x.Name == "header") != null)
{
foreach (var headerValue in jProperty.LastOrDefault(x => x.Name == "header").Value.Children())
table.Columns.Add("[" + headerValue.ToString() + "]");
table.Columns.Add("[ID]");
table.Columns.Add("[comments]");
}
JSON sample:
"DISK" : {
"alarm_count" : 5,
"column_width" : [
12,
14,
16,
14
],
"header" : [
[
"",
"Max Disk Usage",
3
],
[
"Node",
"Percentage",
"Time",
"File System"
]
] }
I can have number of arrays in header .. don't want to hardcode it.. I should be always be able to pick the last array in header child token..Please advise .. thanks

Assuming your json snippet was valid and is part of an object like:
{
"DISK": {
"alarm_count": 5,
"column_width": [
12,
14,
16,
14
],
"header": [
[
"",
"Max Disk Usage",
3
],
[
"Node",
"Percentage",
"Time",
"File System"
]
]
}
}
You could do this:
JObject obj = ...;
var secondHeader = obj["DISK"]["header"].Last();

Related

How to fetch data from Dictionary<string, dynamic> (Json DeserializeObject)

I have Deserialized dynamic Json using Newtonsoft. The JSON is complex and dynamic.
{
"last_updated": " ",
"regions": {
"antarctica": {
"name": "Antarctica",
"totals": [],
"list": [
"aq",
"bv",
"gs",
"tf",
"hm"
]
},
"world": {
"name" : "",
"totals": {
"confirmed": 250566,
"daily_confirmed": 0,
"recovered": 202098,
"deaths": 35205,
"daily_deaths": 0,
"critical": 676,
"tests": 7249844
},
"list": [
{
"country": "Italy",
"country_code": "it",
"state": "Lombardy",
"confirmed": 85775,
"deaths": 15662,
"critical": 231,
"recovered": 231,
"tests": 43442,
"daily_confirmed": -1,
"daily_deaths": -1
}, and so on ..
To overcome the data type issue I have used the dynamic objects
[JsonTypedExtensionData]
public Dictionary<string, dynamic> items { get; set; }
Up to This works well. Now I am trying to fetch the data out of this dynamic Dictionary
var report = await GetCountryReport();
Dictionary<string, dynamic> Dict = report.regions.results["world"].items;
I'm getting data as Dict Count (2)
[0] = {[list, {[ {"country": "Italy","confirmed": 4149,"deaths": 55,"recovered": 2916,"Incidence_Rate": "54.408517127144925","Case-Fatality_Ratio": "1.274822260357931","last_updated": "2020-08-10T22:30:32Z","...
[1] = {[totals, {{"confirmed": 20218306,"recovered": 12814226,"deaths": 737481,"critical": 64743,"tests": 370260493}}]}
How do I fetch the values of each element from the Dictionary like "values.list.country" etc..?
Visual Studio debug - output
You can do it like below:
var list = Dict.Where(x => x.Key == "list").Select(x => x.Value).SingleOrDefault();
var data = ((JArray)list).Select(x => new
{
country = (string)x["country"],
state = (string)x["state"],
confirmed = (int)x["confirmed"]
//...other properties in list
}).ToList();
The data structure is like below:
Then, you can use a foreach loop to get the specify value:
foreach(var x in data)
{
var country = x.country;
var state = x.state;
var confirmed = x.confirmed;
}

merge lists of dictionaries in terraform v0.12

I would like to do the following using terraform:
I have 2 JSONs:
1.json:
[
{
"description": "description1",
"url": "url1",
"data": "data1"
},
{
"description": "description2",
"url": "url2",
"data": "data2",
"action": "action2"
},
{
"description": "description3",
"url": "url3",
"data": "data3"
}
]
2.json:
[
{
"description": "description1",
"url": "url1",
"data": "data1"
},
{
"description": "description2_new",
"url": "url2",
"data": "data2_new"
},
{
"description": "description4",
"url": "url4",
"data": "data4"
}
]
and I want to merge them into one. Dictionaries from the second JSON should override dictionaries from the first one if url key is the same. I.e. combined JSON should look like:
[
{
"description": "description1",
"url": "url1",
"data": "data1"
},
{
"description": "description2_new",
"url": "url2",
"data": "data2_new"
},
{
"description": "description3",
"url": "url3",
"data": "data3"
},
{
"description": "description4",
"url": "url4",
"data": "data4"
}
]
Using python I can easily do it:
import json
with open('1.json') as f:
json1 = json.load(f)
with open('2.json') as f:
json2 = json.load(f)
def list_to_dict(json_list):
res_dict = {}
for d in json_list:
res_dict[d['url']] = d
return res_dict
def merge_json(json1, json2):
j1 = list_to_dict(json1)
j2 = list_to_dict(json2)
j1.update(j2)
res_list = []
for key in j1.keys():
res_list.append(j1[key])
return res_list
print(json.dumps(merge_json(json1, json2), indent=4))
How can I do that using terraform?
Using terraform 0.12.x
$ cat main.tf
locals {
# read from files and turn into json
list1 = jsondecode(file("1.json"))
list2 = jsondecode(file("2.json"))
# iterate over lists and turn url into a unique key
dict1 = { for item in local.list1 : item.url => item }
dict2 = { for item in local.list2 : item.url => item }
# combine both dictionaries so values converge
# only take its values
merged = values(merge(local.dict1, local.dict2))
}
output "this" {
value = local.merged
}
$ terraform apply
Apply complete! Resources: 0 added, 0 changed, 0 destroyed.
Outputs:
this = [
{
"data" = "data1"
"description" = "description1"
"url" = "url1"
},
{
"data" = "data2_new"
"description" = "description2_new"
"url" = "url2"
},
{
"data" = "data3"
"description" = "description3"
"url" = "url3"
},
{
"data" = "data4"
"description" = "description4"
"url" = "url4"
},
]
Terraform supports expanding a list into function parameters using the ... operator. This will allow an arbitrary number of documents to be read.
(I'm not sure, but I believe this feature was added in v0.15)
For this example, I added a new file 3.json with the contents:
[
{
"description": "description4_new",
"url": "url4",
"data": "data4_new"
}
]
For main.tf, I'm using the same logic as #someguyonacomputer's answer:
$ cat main.tf
locals {
jsondocs = [
for filename in fileset(path.module, "*.json") : jsondecode(file(filename))
]
as_dicts = [
for arr in local.jsondocs : {
for obj in arr : obj.url => obj
}
]
# This is where the '...' operator is used
merged = merge(local.as_dicts...)
}
output "as_list" {
value = values(local.merged)
}
Result:
Changes to Outputs:
+ as_list = [
+ {
+ data = "data1"
+ description = "description1"
+ url = "url1"
},
+ {
+ data = "data2_new"
+ description = "description2_new"
+ url = "url2"
},
+ {
+ data = "data3"
+ description = "description3"
+ url = "url3"
},
+ {
+ data = "data4_new"
+ description = "description4_new"
+ url = "url4"
},
]
References:
Terraform Docs -- Function Calls # Expanding Function Arguments

Es6: Create an array of objects from a json

I have a json in the below format.
[
{"id": 1,
"name": "peter" },
{"id": 2,
"name": "john" },
{"id": 3,
"name": "justin" }
.
.
{"id": 500,
"name": "david" },
]
I am trying to create an array in batches of 10 in the below format
[
{
{"id": 1,
"name": "peter" },
.
.
{"id": 10,
"name": "nixon" },
},
{
{"id": 11,
"name": "nancy" },
.
.
{"id": 20,
"name": "underwood" },
}
.
.
]
I tried using reduce and tried for loop to loop through it, but was unsuccessful
Here's a demo.
const str = "abcdefghigklmnopqrstuvwxyz";
let data = [];
for(let i = 0; i < 26; i++){
data.push({id : i, name: str.charAt(i)});
}
let res = data.reduce((acc, d) => {
let groupId = Math.floor(d.id / 10);
acc[groupId] = acc[groupId] || {};
acc[groupId][d.id] = d;
return acc;
}, {});
console.log(Object.values(res));
If you can ensure that id is the same sequence as their position in array, i think simply slice will better.

how to print json array in jsonobject when we will get element of jsonarrray at runtime

ArrayList al = new ArrayList();
//al[0] and al[1] are the json objects.
def json = new JsonBuilder()
json {
type "rel12"
total k
xyz ""
shows al[0],al[1]
emails ""
}
println json.toPrettyString()
i dont want to do the the hardcoding like al[0]. al[1].
but i need the output like
{
"type": "rel12",
"total": 2,
"xyz": "",
"shows": [
{
"extension": "zip",
"updateTime": 1477521104511
},
{
"extension": "zip",
"updateTime": 1477521104623
}
],
"emails": ""
}

How to pass list of objects in json object

Hi I am developing small application in which I am trying to pass some data in http post method. So I want to send my data like this form
"storeid": "151",
"floordata": {
"entry": [
10,
15
],
"exit": [
10,
15
],
"section": [
{
"id": "0",
"sectionname": "ABC",
"category": "office",
"boundary": [
[
85,
258
],
[
85,
298
],
[
125,
298
],
[
125,
258
],
[
85,
258
]
"description": "Mobile based company"
}
]
},
"category": null,
"description": null
so my problem is regarding section parameter. I am doing this for section parameter.
String section = "section=";
// Problem for me is here ...
JSONArray sections = new JSONArray();
List<List<Float>> sectionCords = new ArrayList<List<Float>>();
List<Float> sectionCordData = new ArrayList<Float>();
sectionCordData.add(0.0f);
sectionCordData.add(0.1f);
List<Float> sectionCordData1 = new ArrayList<Float>();
sectionCordData1.add(0.0f);
sectionCordData1.add(0.1f);
sectionCords.add(sectionCordData);
sectionCords.add(sectionCordData1);
JSONObject sectionObj = new JSONObject();
//List<JSONObject> cordList = new ArrayList<JSONObject>();
try {
sectionObj.put("category", "office");
sectionObj.put("description", "Mobile based company");
sectionObj.put("sectionname", "mobiotics");
sectionObj.put("id", 0);
sectionObj.put("boundary", sectionCords); // Check Here i am sending as list ...
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sections.put(sectionObj);
section += sections;
section +="&";
But In actual it my section boundary parameter going as string instead of list. Like this
boundary=[
[
0.0,
0.1
],
[
0.0,
0.1
]
],storeid=156&floor=2&section=[
{
"id": 0,
"sectionname": "mobiotics",
"category": "office",
"boundary": "[[0.0, 0.1], [0.0, 0.1]]", // See here is my problem ...
"description": "Mobile based company"
}
],entry=[
10,
15
],exit=[
10,
15
]
How to send it as list instead of string. Need Help. Thank you.
Define sectionChords, and sectionCordData* as JSONArray instead of List:
JSONArray sectionChords = new JSONArray();
JSONArray sectionCordData = new JSONArray();
sectionCordData.put(0.0f);
sectionCordData.put(0.1f);
JSONArray sectionCordData1 = new JSONArray();
sectionCordData1.put(0.0f);
sectionCordData1.put(0.1f);
sectionCords.put(sectionCordData);
sectionCords.put(sectionCordData1);
It must do what you want according to docs.
Put a key/value pair in the JSONObject, where the value will be a JSONArray which is produced from a Collection.
But it puts JSON representation of your object as String. So you should use either JSONArrays or Java objects. You should not mix them.
controller :
public JsonResult Index()
{
List<Location> location = (from a in db.Locations select a).ToList();
return Json(location, JsonRequestBehavior.AllowGet);
}