How to use JObject.FromObject to get a json with no propertyname - json

I use NewtonSoft JSON.Net. I have a collection of namevalue pair and i need to get a json that looks like
{"cot":"1","mac":"2","cot":"8"}
Note that i can have duplicate names here.
I have two options here
a) i can use Dictionary as my underlying collection and when i do, i get the desired result but i cant add duplicate key.
b) i have have a list of KeyValuePair but in this case, the result json is not in the structure i wanted.
Any idea how to get the desired result? thanks!
var listData = new List<KeyValuePair<string, string>>();
listData.Add(new KeyValuePair<string, string>("cot", "1"));
listData.Add(new KeyValuePair<string, string>("mat", "1"));
listData.Add(new KeyValuePair<string, string>("cot", "2"));
var dicData = new Dictionary<string, string>();
dicData.Add("cot", "1");
dicData.Add("mat", "1");
Console.WriteLine("Output from LIST");
Console.WriteLine(JArray.FromObject(listData));
Console.WriteLine();
Console.WriteLine("Output from Dictionary");
Console.WriteLine(JObject.FromObject(dicData));
Output from LIST
[
{
"Key": "cot",
"Value": "1"
},
{
"Key": "mat",
"Value": "1"
},
{
"Key": "cot",
"Value": "2"
}
]
Output from Dictionary
{
"cot": "1",
"mat": "1"
}

The JSON
'{"cot":"1","mac":"2","cot":"8"}'
will parse to a javscript object :
{"cot":"8","mac":"2"}.
Try
dicData.Add("cot", "8")
and see if it gets what you want.
You can also try concatenating strings until you get the desired JSON.
Like
var jsonOutput = "{"
//for each key value...
jsonOutput += "key : "+ value.toString + ","
//...etc
//then remove the last trailing comma, and add a "}"

Related

Unable to get json node values

This is the json response format that I have and need to read the first node value "html". I have tried to few ways to get the value but unable to get it
[
{
"html": "<!DOCTYPE html>\n <html>\n <head>\n <\/html>\n \n",
<\/html>\n \n",
"headers": {},
"subject": "Register new account",
"messageId": "475603953.247.1565607800153#dfrsbdd201.abc.com.au",
"priority": "normal",
"from": [],
"to": [],
"date": "2019-08-12T11:03:20.000Z",
"receivedDate": "2019-08-12T11:09:42.000Z",
"receivedAt": "2019-08-12T11:09:44.900Z"
},
{+},
{+}
]
I tried couple of things
RequestSpecification emailReq = given().with().pathParam("email",emailName);
Response emailResp = emailReq.contentType("application/json").get("https://restmail.net/mail/{email}");
JSONObject value = new JSONObject(emailResp.asString());
I got this error
org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]
at org.json.JSONTokener.syntaxError(JSONTokener.java:505)
and then I removed this last line to use But this does not gives me error. pls refer screenshot for this
JSONArray responseJson = new JSONArray(emailResp.asString());
Tried this as well
List<HashMap<String, Object>> jsonObjectsInArray = emailResp.jsonPath().getList("$");
for (HashMap<String, Object> singleLeg : jsonObjectsInArray) {
String value = (String) singleLeg.get("html");
}
But again array size is 0
Need some suggestion of how to get the value of node - "html". Pls suggest. what mistake am I doing here?
Thanks in advance
RequestSpecification emailReq = given().with().pathParam("email",emailName);
int retries = 5;
List<HashMap<String, Object>> emails = Arrays.asList();
. . .
emailResp = emailReq.get("restmail.net/mail{email}");
if (emailResp.getStatusCode() == 200) { emails = emailResp.jsonPath().getList("$");
String email = emails.get(0).get("html").toString();

Getting element value from jsonpath whose root is an array

I have a JSON response which has root as an array of 1 or more objects. I want to extract the value of one of the elements within each object.
Here is the JSON sample:
[
{
"od_pair":"7015400:8727100",
"buckets":[
{
"bucket":"C00",
"original":2,
"available":2
},
{
"bucket":"A01",
"original":76,
"available":0
},
{
"bucket":"B01",
"original":672,
"available":480
}
]
},
{
"od_pair":"7015400:8814001",
"buckets":[
{
"bucket":"C00",
"original":2,
"available":2
},
{
"bucket":"A01",
"original":40,
"available":40
},
{
"bucket":"B01",
"original":672,
"available":672
},
{
"bucket":"B03",
"original":632,
"available":632
},
{
"bucket":"B05",
"original":558,
"available":558
}
]
}
]
I want to access the values of od_pair within each object.
I tried referring to the root array as $ but that did not help.
This is the code snippet I have written:
List<Object> LegList = jsonPath.getList("$");
int NoofLegs = LegList.size();
System.out.println("No of legs :" +NoofLegs);
for (int j=0; j<=NoofLegs;j++) {
String OD_Pair = jsonPath.param("j", j).getString("[j].od_pair");
System.out.println("OD Pair: " + OD_Pair);
List<Object> BucketsList = jsonPath.param("j", j).getList("[j].buckets");
int NoOfBuckets = BucketsList.size();
System.out.println("no of Buckets: " + NoOfBuckets);
}
This is the error that I see:
Caused by:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup
failed:
Script1.groovy: 1: unexpected token: [ # line 1, column 27.
restAssuredJsonRootObject.[j].od_pair
Can someone kindly help me here please?
You were right to start with the $. However, What you get with your particular JSON is List of HashMap<String, Object> where each JSON Object is represented as a single HashMap. Knowing that you can obtain the list of HashMaps like this:
List<HashMap<String, Object>> jsonObjectsInArray = path.getList("$");
The String will be the name of the attribute. The Object will be either String, Integer, JSONObject or JSONArray. The latter isn't exact class names but it's not relevant to you to achieve desired results.
Now, all we have to do is iterate over the HashMap and extract values of od_pair like this:
for (HashMap<String, Object> jsonObject : jsonObjectsInArray) {
System.out.println(jsonObject.get("od_pair"));
}
The output is:
7015400:8727100
7015400:8814001
Hope it helps!

How can i list the values of a Node in JSON ?

Say, I have a JSON that has an array of "Topics"
I need to list all "created_at" values of all the topics
without the other data , using the Chrome console
P.S : I'm Using JSONView
You can loop through the objects in your array and simply access the property created_at.
Example
var json = {
all_topics: [{
"created_at:" "2016-08-08T10:22:03.123Z",
"name": "topic1"
}, {
"created_at": "2016-08-08T11:43:06.963Z",
"name": "topic2"
}]
}
for (var topic of json.all_topics) {
console.log(topic.created_at);
}
You can use JSON.stringify to turn a JavaScript object into a JSON String, and JSON.parse to turn a JSON string into a JavaScript object.
var jsonString = JSON.stringify(json);
==> {"all_topics":[{"created_at":"2016-08-08T10:22:03.123Z","name":"topic1"},{"created_at":"2016-08-08T11:43:06.963Z","name":"topic2"}]}
var jsonObj = JSON.parse(jsonString);
==> Object {all_topics: Array[2]}
Alternatively, you could return a new array with the filtered property using Array.prototype.map:
var topics = json.all_topics.map(function(obj){
return obj.created_at;
});
==> ["2016-08-08T10:22:03.123Z", "2016-08-08T11:43:06.963Z"]

JSON.net parsing of dynamic JSON

I have JSON that looks like this:
{
"status": {
"code": 0,
"message": "OK"
},
"data": {
"_idtype": "cusip",
"_id": "00768Y883",
"api": {
"_name": "PortfolioBreakdownsRaw",
"PortfolioDate": "2015-10-12",
"GlobalBondSuperSectorLongSalePositionBreakdown": [
{
"Name": "Municipal",
"Value": "0.57842"
},
{
"Name": "Corporate",
"Value": "1.79649"
},
{
"Name": "Securitized",
"Value": "5.29493"
},
{
"Name": "Cash & Equivalents",
"Value": "166.20776"
}
],
"GlobalBondSuperSectorShortSalePositionBreakdown": [
{
"Name": "Government",
"Value": "0.90557"
}
]
}
}
}
I am able to get the api portion of the response easily:
var jObject = JObject.Parse(json);
var api = jObject["data"]["api"];
From here, I don't what if any arrays will be included in the response. The ultimate goal will be to create a parser that will be able to get the array names (GlobalBondSuperSectorShortSalePositionBreakdown) and as many rows of key-value pairs that it may contain, without first knowing the names such as (GlobalBondSuperSectorShortSalePositionBreakdown) beforehand.
I can't seem to find a good way to loop through the object, determine there are arrays at the api level and then iterate through those to get the values.
Any help would be appreciated.
Here's an example. In this code, the api variable holds a JObject, so we can iterate over its properties. From there, we look at the Type of each property value to see if it is an array or not. If it is, then we can iterate over that array to get the JObjects within it, and extract the Name and Value values that we expect to find there. Does this help?
var jObject = JObject.Parse(json);
var api = jObject["data"]["api"];
foreach (JProperty prop in api.Children<JProperty>())
{
JToken value = prop.Value;
if (value.Type == JTokenType.Array)
{
Console.WriteLine(prop.Name + ": ");
foreach (JObject jo in value.Children<JObject>())
{
Console.WriteLine(" " + jo["Name"] + ": " + jo["Value"]);
}
}
else
{
Console.WriteLine(prop.Name + ": " + value);
}
}
Output:
_name: PortfolioBreakdownsRaw
PortfolioDate: 2015-10-12
GlobalBondSuperSectorLongSalePositionBreakdown:
Municipal: 0.57842
Corporate: 1.79649
Securitized: 5.29493
Cash & Equivalents: 166.20776
GlobalBondSuperSectorShortSalePositionBreakdown:
Government: 0.90557
Fiddle: https://dotnetfiddle.net/XyoXQy
With Linq you can play pretty nice with Json.net:
Here is an easily readable version of the chunk of code that will create two dictionaries out of the JArray properties under the api element:
var api = jObject["data"]["api"];
var arrays = api.Cast<JProperty>().Where(o => o.Value.Type == JTokenType.Array).Select(token => token.Value).ToArray();
var dictionaries = new List<Dictionary<string, string>>();
foreach (var array in arrays)
{
var dictionary = array.ToDictionary(token => token["Name"].Value<string>(), token => token["Value"].Value<string>());
dictionaries.Add(dictionary);
}
alternative:
The same thing, but a shorter, more compact version :
var api = jObject["data"]["api"];
var dictionaries = api
.Cast<JProperty>()
.Where(o => o.Value.Type == JTokenType.Array)
.Select(token => token.Value)
.Select(array => array.ToDictionary(token => token["Name"].Value<string>(), token => token["Value"].Value<string>()));

Index of a numbered array of key:value in Mustache.js

I have this object:
{nodes: [
{
node: {
actors: {
1: "Actor 1",
2: "Actor 2"
}
}
}]
In my Mustache template, I tried this and it worked:
{{#actors}}
{{1}}<br />
{{2}}
{{/actors}}
But I dont know how much actors I have, I need something like an index. It seems that handlebars.js knows how to do this, but I want to use Mustache.js.
I would change the format of the JSON so it is like:
"actors": [ {"name": "Actor 1"}, {"name": "Actor 2"}]
Then you can do
{{#actors}}
{{name}}
{{/actors}}
If you wanted to use Handlebars, you can specify a helper for this:
Handlebars.registerHelper('eachProperty', function (context, options) {
var ret = "";
for (var prop in context) {
if (prop)
ret = ret + options.fn(({ property: prop, value: JSON.stringify(context[prop]) }));
}
return ret;
});
So when you wanted to iterate over an object's properties, you can do:
{{#eachProperty actors}}
{{value}}
{{/eachProperty}}
Also note that {{property}} would give you the index value for the object.