Counting JSON nodes - json

How to calculate the how many objects in JSON object
my code is
String json = IOUtils.toString(is);
JSONObject jo = new JSONObject(json);
Here 'jo' is the jsonobeject with in that object some data is there that data is:
{
"cargoDetails":[{
"noOfPackages":"2",
"packType":"AUG",
"uom":"LB",
"packLength":"10",
"actualWt":"5",
"packHeight":"2",
"packWidth":"4",
"packDescription":"description",
"currId":"1",
"shipmentMode":"1"},
{"noOfPackages":"2",
"packType":"BAG",
"uom":"KG",
"packLength":"10",
"actualWt":"5",
"packHeight":"2",
"packWidth":"4",
"packDescription":"description",
"currId":"1",
"shipmentMode":"1"}],
"type":"air",
"userId":"KOTESWAR",
"customerId":"CUST00168",
"contractId":"CONTRACT0000576",
"originTerminalId":"FINBOM",
"destinationTerminalId":"FINDEL",
"ShipperId":"CUST00003",
"serviceLevelId":"STD",
"paymentTerms":"Prepaid",
"terminalId":"FINBOM",
"originDepartment":"AE",
"destinationDepartment":"AI",
"departurePort":"INBOM",
"destinationPort":"BOM",
"totalNoPcs":"4",
"totalActualWt":"5",
"totalVol":"10"
}
k with in that i can send cargodetails objects 2 remaining are bookingdetails
so my question is how to find the how many objects are there in jO.
because with that jo only i can iterate the loop.

If you are asking about how to define how many keys are in object, you should use Object.keys(json), which returns an array with all own keys. Yet, it is rather new function, not implemented in all browsers that are currently in use. Without Object.keys you have to use (for key in json) loop, testing each key with hasOwnProperty.
By the way, hasOwnProperty also can be not implemented in some browsers.

Related

How to access the key of a jsoncpp Value

I kind of feel stupid for asking this, but haven't been able to find a way to get the key of a JSON value. I know how to retrieve the key if I have an iterator of the object. I also know of operator[].
In my case the key is not a known value, so can't use get(const char *key) or operator[]. Also can't find a getKey() method.
My JSON looks like this:
{Obj_Array: [{"122":{"Member_Array":["241", "642"]}}]}
For the piece of code to parse {"122":{"Member_Array":["241", "642"]}} I want to use get_key()-like function just to retrieve "122" but seems like I have to use an iterator which to me seems to be overkill.
I might have a fundamental lack of understanding of how jsoncpp is representing a JSON file.
First, what you have won't parse in JsonCPP. Keys must always be enclosed in double quotes:
{"Obj_Array": [{"122":{"Member_Array":["241", "642"]}}]}
Assuming that was just an oversight, if we add whitespace and tag the elements:
{
root-> "Obj_Array" : [
elem0-> {
key0-> "122":
val0-> {
key0.1-> "Member_Array" :
val0.1-> [
elem0.1.0-> "241",
elem0.1.1-> "642" ]
}
}
]
}
Assuming you have managed to read your data into a Json::Value (let's call it root), each of the tagged values can be accessed like this:
elem0 = root[0];
val0 = elem0["122"]
val0_1 = val0["Member_Array"];
elem0_1_0 = val0_1[0];
elem0_1_1 = val0_1[1];
You notice that this only retrieves values; the keys were known a priori. This is not unusual; the keys define the schema of the data; you have to know them to directly access the values.
In your question, you state that this is not an option, because the keys are not known. Applying semantic meaning to unknown keys could be challenging, but you already came to the answer. If you want to get the key values, then you do have to iterate over the elements of the enclosing Json::Value.
So, to get to key0, you need something like this (untested):
elem0_members = elem0.getMemberNames();
key0 = elem0_members[0];
This isn't production quality, by any means, but I hope it points in the right direction.

Why does encoding an array into json format result in an json object?

This is strange, I've used json encoding arrays and the output is something like [{" etc, but in another code this time the output is "{"1":{".. causing multiple errors. I don't understand what is going on.
this is the part of the code:
$json_arr = json_decode($json_str, true);
$fecha = date("Y-m-d H:i:s");
foreach (array_column($json_arr, 'f') AS $k => $fecha) {
if($fecha < $ahora){
unset($json_arr[$k]);
}
}
$json_str = json_encode($json_arr,true);//this will be inserted in the DB table
but the $json_str is in the form of "{"1":{".. but I need in the form of [{".
Here some of the images when debugging:
in orange, the json_str is readed from the BD table
after decoding, you see the json_arr is an array of three elements
after deleting some row, you see json_arr is still an array
after encoding the json_arr, I get the "{"1":{" format, in other cases of encoding arrays I had the [{" format, which is what I need.
You are starting with an array of 3 arrays, with the indices of 0, 1, and 2.
Then you are deleting the first one. If you compare your 2nd and 3rd screenshots, specifically the popup portion, you'll see that what you have lost is index 0. Your array now starts with index 1.
But in JavaScript, an array can't start with index 1. It has to start with index 0, so PHP is encoding it as an object, instead of an array.
If you use the PHP function array_values() it will re-index your array and you should be good to go.

How to check if JSON response fields are alphabetically sorted?

How to validate the JSON Response fields? After validating the fields I need to check whether the fields are alphabetically sorted or not. How would I do it ?
The JSON object is unordered set of name/value pairs. There is no guarangee of ordering at all. You need to take json object keys list and sort them. After sorting access to object fields by sorted keys list.
If you mean how to check list (array) of values. You need to implement simple loop through array and check that each element must be less than next element in sorting comparision criteria.
For js language checking array for alpha ordering may be done like this:
var array = ["Apple", "Application", "AppName", "Happy"];
var isSortedAlpha = array.reduce(function(res, current, index, arr) {
return res && arr[index&&index-1] <= current
}, true);

How to get info from an object created from json

I have a json string: {"jsonrpc":"2.0","result":[{"event":{"id":"27151641","name":"TSW Pegasus FC (Res) v Sun Hei SC (Res)","countryCode":"HK","timezone":"GMT","openDate":"2014-02-19T12:30:00.000Z"},"marketCount":14},{"event":{"id ":"27151646","name":"Humble Lions v Boys Town FC... etc etc
So the result bit is a list of event/marketcount pairs. I've used the parse method in a class module called jsonlib which I got from http://code.google.com/p/vba-json/issues/attachmentText?id=15&aid=150001000&name=jsonlib.cls&token=31ObtlGBtaGXd2KR0QLyffX_x8Y:1359742317106
This creates an object (jason_obj) which represents the result bit above. Now I want to get a list of ids for each event. I can use the for each ... construct to return each event/marketcount pair as an object, but I can't work out how to get to the id field that is somewhere in the event object. I tried to use the tostring method to get a clue, and from that this code should work but it doesn't:
For Each eventItem In jason_obj
this_eventx = eventItem("event")
this_id = this_eventx("id")
Next
Don't know much about accessing objects/collections. Can anyone help? Thanks
Objects need to be set and references should use item:
For Each eventItem In jason_obj
set this_eventx = eventItem.item("event")
this_id = this_eventx.item("id")
Next
HTH
Yes it did

Using JSON Data with Coldfusion

I've worked with JSON data in the past - mainly 'fudging' my way to a solution, and not really understanding why or how things work. I've come across an issue where the data being returned looks somewhat different to what I've seen before, and I can't find any examples that match it.
Here's an example of the data returned (via an API);
{"domain.co.uk":{"status":"available","classkey":"thirdleveldotuk"},"domain.net":{"status":"available","classkey":"dotnet"},"domain.com":{"status":"available","classkey":"domcno"}}
On my front-end, I need to return something like this -
domain.co.uk - available
domain.net - available
domain.com - available
Because the 'domain.com' etc value will always change, I can't map the names as I usually would (although it will always be 3 'rows' returned)
I've checked every CF Book I own, and read the online CF Docs, but I'm totally at a loss as to where to even start with this one!
Pointers much appreciated!
If you run this with deserializeJSON(data), you'll see that you just end up with structures with nested structures. So, you can loop through your struct, grab the keys and then grab that key's status. In JSON terms, your JSON object has nested objects.
<cfset data = deserializeJSON(apiData) />
<cfset formattedData = [] />
<cfset tmp = {} />
<cfloop collection=#data# item="domain">
<cfset tmp.domain = domain />
<cfset tmp.status = data[domain]["status"] />
<cfset arrayAppend(formattedData,duplicate(tmp)) />
</cfloop>
<cfdump var=#formattedData# />
(This is really more of a comment, but is a bit too long ... )
I've worked with JSON data in the past - mainly 'fudging' my way to a
solution, and not really understanding why or how things work
JSON strings are essentially just a representations of two objects:
arrays which are denoted by [] and
structures (or objects) which are denoted by {}
Looking at the API string, the braces {} indicate you are dealing with a structure:
{ "theKey": "theValue" }
In your case, the domain name is the structure key:
{ "domain.co.uk": "theValue" }
.. and the value is a nested structure containing two static keys: "status" and "classkey"
{ "theKey": {"status":"available","classkey":"thirdleveldotuk"} }
As with any structure, you can iterate through the keys dynamically using a for .. in loop, a collection loop if you prefer cfml.
for (theKey in theStruct) {
WriteDump( theKey ); // ie "domain.co.uk"
}
Then inside the loop use associative array notation to grab the value, ie:
theStatus = theStruct[ theKey ]["status"]; // "available"
// ... OR
theValue = theStruct[ theKey ];
theStatus = theValue.status;
That is all there is to it. You can use similar logic to access any type of nested structures.