How to read nested JSON in Codename One - codenameone

I have been following the instructions here:
https://www.codenameone.com/javadoc/com/codename1/io/JSONParser.html to retrieve a value from a json file.
I have managed to read the top level value of my json content - however I cannot see how to read the value of a nested tag e.g. using this file ...
{
"glossary":{
"title":"example glossary",
"GlossDiv":{
"title":"S",
"GlossList":{
"GlossEntry":{
"ID":"SGML",
"SortAs":"SGML",
"GlossTerm":"Standard Generalized Markup Language",
"Acronym":"SGML",
"Abbrev":"ISO 8879:1986",
"GlossDef":{
"para":"A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso":[
"GML",
"XML"
]
},
"GlossSee":"markup"
}
}
}
}
}
Please can someone show me how to get to the value of "para" above?
Thanks

After parsing your json data based on this, you can use Result to read deep into the json content:
import com.codename1.processing.Result;
...
Map<String, Object> data = json.parseJSON(r);
Result result = Result.fromContent(data);
String id = result.getAsString("glossary/GlossDiv/GlossList/GlossEntry/ID");
String para = result.getAsString("glossary/GlossDiv/GlossList/GlossEntry/GlossDef/para");

Related

Map the Array in to the each individual JSON so the records can be created

I am trying to convert the below Array in to the JSON, trying by iterating through the Array and transforming. The array looks like below
Quote_Sent_To__r = [
{
Quote__c=0Q02D05XGQSA2,
Id=a1H2D0m94QUAQ,
type=QuoteSentTo__c
},
{
Quote__c=0Q02D00XGQSA2,
Id=a1H2D00000AQ,
type=QuoteSentTo__c
}
]
I have stored the array in to the variable quoteSentToList and iterating through the for loop
Within each iteration I need to get the JSON like
{
"Quote__c": "0Q02D05XGQSA2"
}
So this can be passed to the Salesforce Update operation. I tried like
%dw 2.0
output application/json
var item = vars.quoteSentToList[counter]
---
{
"Quote__c" :payload.Id
}
It errors saying
Reason: Unable to resolve reference of: counter..
Scripting language error on expression 'payload'. Reason: Unable to resolve reference of: payload..
This is my first project and any help is greatly appreciated
Error
""Unexpected character 'v' at quoteSentToList#[1:1] (line:column), expected false or true or null or {...} or [...] or number but was , while reading quoteSentToList as Json.
1| vars.existingQuote[0].Quote_Sent_To__r ^" evaluating expression: "%dw 2.0 output application/json
---
vars.quoteSentToList map { Quote__c: payload.Id, Id: $.Id }"."
counter is a Mule variable, not a DataWeave variable. You need to use the prefix vars. to reference it inside DataWeave scripts: vars.counter.
Alternatively, instead of using a <foreach> scope, you can transform the entire array at once and then use each element as needed:
%dw 2.0
output application/json
---
vars.quoteSentToList map { Quote__c: $.Id }
Output:
[
{
"Quote__c": "a1H2D0m94QUAQ"
},
{
"Quote__c": "a1H2D00000AQ"
}
]

How to extract data from an API and create an array to send to the another API in Jmeter?

Example:
API A:
{
"customer":[
{
"name":"Jane",
"phone":"9999999",
"email":"jane#test.com"
},
{
"name":"John",
"phone":"8888888",
"email":"john#test.com"
},
{
"name":"Joe",
"phone":"7777777",
"email":"Joe#test.com"
}
]
}
Using the JSON extractor, I want to get the names of all the customers
so: Jane, John, Joe
How do I get these values and turn them into an array
[{"name":"Jane", "name":"John", "name":"Joe"}]
And pass it onto the next API?
Note: That it has to be dynamic so API A could show different 2 names or 1 name or more and needs to be adjusted into the array
First of all your [{"name":"Jane", "name":"John", "name":"Joe"}] is not a valid JSON, you can check it yourself:
so I strongly doubt that this is the string you need to generate.
So if you really need to construct this value you can do something like:
Add JSR223 PostProcessor as a child of the request which returns this "customers" data
Put the following code into "Script" area:
def response = new groovy.json.JsonSlurper().parse(prev.getResponseData())
def payload = new StringBuilder()
payload.append('[{')
0.upto(response.customer.size - 1, { index ->
payload.append('"name": "').append(response.customer[index].name).append('"')
if (index != response.customer.size - 1) {
payload.append(',')
}
})
payload.append('}]')
vars.put('payload', payload as String)
Refer the generated value as ${payload} where required
Demo:
More information:
JsonSlurper
Apache Groovy - Parsing and producing JSON
Apache Groovy - Why and How You Should Use It

How to pass an Encoded ("application/x-www-form-urlencoded") object with array within a query string in HttpClient?

I am trying to encode ("application/x-www-form-urlencoded") an object in Angular using HttpParameterCodec.
This object has a field as object which in turn has array of string. object structure as mentioned below.
export class SearchRequest {id: string = undefined;partnerIds: PartnerIds = undefined;}
export class PartnerIds { partnerId: string[] = undefined;}
Now when I am trying encode this object with utility code (which works fine with plain object) mentioned below, It is not in correct format due to list of string in it.
generateQueryParams(searchRequest) {
let httpParams: HttpParams = new HttpParams({encoder: new CustomEncoderComponent()});
Object.keys(searchRequest).forEach(key => {
httpParams = httpParams.append(key, searchRequest[key]);
});
return httpParams;
}
I tried with below query params format but it did not work.
1. id=123&partnerIds=XYZ&partnerIds=ABC
2. id=123&partnerId[]=XYZ&partnerId[]=ABC
3. id=123&partnerId=XYZ&partnerId=ABC
Please suggest How to pass this (SearchRequest) object within a query string in HttpClient?

FullCalendar JSON not populating calendar

I think I am missing something. I have set up Full Calendar, and have the default version working, but now am adding my own JSON, and it is not.
Code in the calendar page is
$(document).ready(function() {
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay,listWeek'
},
defaultDate: '2017-09-12',
editable: true,
navLinks: true, // can click day/week names to navigate views
eventLimit: true, // allow "more" link when too many events
events: {
url: 'php/get-events.php',
error: function() {
$('#script-warning').show();
}
},
loading: function(bool) {
$('#loading').toggle(bool);
}
});
});
I am learning how to encode JSON as I go along, and I found a tutorial online that gave me some code that seems to work. I have amended the original code in get-events.php to read like this (snippet with DB details taken out)...
// Require our Event class and datetime utilities
require dirname(__FILE__) . '/utils.php';
// Short-circuit if the client did not give us a date range.
if (!isset($_GET['start']) || !isset($_GET['end'])) {
die("Please provide a date range.");
}
// Parse the start/end parameters.
// These are assumed to be ISO8601 strings with no time nor timezone, like "2013-12-29".
// Since no timezone will be present, they will parsed as UTC.
$range_start = parseDateTime($_GET['start']);
$range_end = parseDateTime($_GET['end']);
// Parse the timezone parameter if it is present.
$timezone = null;
if (isset($_GET['timezone'])) {
$timezone = new DateTimeZone($_GET['timezone']);
}
class Emp {
public $id = "";
public $title = "";
public $start = "";
public $url = "";
}
while(!$JAN->atEnd()) {
e = new Emp();
$e->id = $JAN->getColumnVal("ID");
$e->title = $JAN->getColumnVal("TITLE");
$e->start = $JAN->getColumnVal("DATE")."T".$JAN->getColumnVal("TIME");
$e->url = "meeting_info.php?ID=".$JAN->getColumnVal("ID");
echo json_encode($e);
$JAN->moveNext();
}
$JAN->moveFirst(); //return RS to first record
// Read and parse our events JSON file into an array of event data arrays.
$json = file_get_contents(dirname(__FILE__) . '/../json/events.json');
$input_arrays = json_decode($json, true);
// Accumulate an output array of event data arrays.
$output_arrays = array();
foreach ($input_arrays as $array) {
// Convert the input array into a useful Event object
$event = new Event($array, $timezone);
// If the event is in-bounds, add it to the output
if ($event->isWithinDayRange($range_start, $range_end)) {
$output_arrays[] = $event->toArray();
}
}
// Send JSON to the client.
echo json_encode($output_arrays);
When I run the get-events.php page on it's own I get what I am assuming to be a correctly encoded JSON returned, one example in the array is ...
{"id":20,"title":"Executive Committee Meeting","start":"2017-05-01T00:00:00","url":"meeting_info.php?ID=20"}
Can anybody tell me what I have done wrong?
You need to run json_encode() on a complete array of PHP objects, not on each one individually. In your loop, add each Emp to an array, and then encode the array, when the loop ends.
If you look in your browser's network tab at the result of your ajax request, I think you're very likely to see a string of individual objects, but not wrapped in array (square) brackets, and not separated by commas, meaning the JSON is invalid. There's also a good chance there's an error message in your browser's console about the invalid data format. It's best to check this rather than assuming your JSON is correct. There are also online JSON validator tools you can paste it into, to validate the JSON in isolation.
Something like this should work better:
$events = array();
while(!$JAN->atEnd()) {
e = new Emp();
$e->id = $JAN->getColumnVal("ID");
$e->title = $JAN->getColumnVal("TITLE");
$e->start = $JAN->getColumnVal("DATE")."T".$JAN->getColumnVal("TIME");
$e->url = "meeting_info.php?ID=".$JAN->getColumnVal("ID");
$events[] = $e; //add event to the array
$JAN->moveNext();
}
echo json_encode($events); //encode the whole array as a coherent piece of JSON
//P.S. no need to run moveFirst really, since the request is going to end, and discard the resultset anyhow. Depending on your data access technique, you possibly need to close the recordset though, to avoid locking etc.
What you need your code to generate (and what fullCalendar is expecting), is a JSON array - here's a simple example containing 2 elements (representing events):
[
{ "id":20, "title":"Executive Committee Meeting", "start":"2017-05-01T00:00:00", "url":"meeting_info.php?ID=20" },
{ "id":21, "title":"Another Boring Committee Meeting", "start":"2017-05-02T00:00:00", "url":"meeting_info.php?ID=21" }
]
The example code I've given above should generate an array which is in the same format as this JSON sample.

how to parse nested json object

I am using json parser lib written in C to parse JSON objects. The lib link is : https://github.com/udp/json-parser.
The json object/string, which I am trying to parse is :
{"video_id": 105, "st": "S3", "processing" : [{"start" : "1", "end" : "2"}]}}
"processing" contains another JSON object.
I have parsed the first three items. But I am not able to figure out a way to parse the "processing" json object. I am using following code:-
if (!strcmp(json->u.object.values[i].name, "video_id"))
{
video_id=json->u.object.values[i].value->u.integer;
}
.
.
if (!strcmp(json->u.object.values[i].name, "processing"))
{
printf("\nNumber of JSON OBJECTS : %d\n", json->u.object.values[i].value->u.object.length);
}
json is the parsed object obtained via calling the lib on the JSON string. Can anyone guide me how to handle the nested object ?
Any help will be really appreciated
My complete code is :
json_value *json;
json_char *json_object="{\"video_id\": 105, \"st\": \"S3\", \"processing\" : [{\"type\" : \"clipping\"},{\"fese\" : \"dipping\"}]}";
printf("%s",json_object);
//json_value * json_parse (const json_char * json,
// size_t length);
json=json_parse(json_object, strlen(json_object));
// json_type json_object;
printf("\n%s\n",json->u.object.values[0].name);
printf("\t%d\n",json->u.object.values[0].value->u.integer);
printf("\n%s\n",json->u.object.values[2].name);
printf("\t%d\n",json->u.object.values[2].value->u.object.length);
printf("\t%s\n",json->u.object.values[2].value->u.object.values[0].name);
From the documentation, API field::
The type field of json_value is one of:
json_object (see u.object.length, u.object.values[x].name, u.object.values[x].value)
json_array (see u.array.length, u.array.values)
json_integer (see u.integer)
json_double (see u.dbl)
json_string (see u.string.ptr, u.string.length)
json_boolean (see u.boolean)
json_null
So, check the type field of the "processing" value. If found to be json_array, do a json_parse for the array to get a new json_value. Now this json_value will provide you with the nested JSON objects.
Take these as reference:
js_v->u.object.values[1].value->u.array.values[0]->type
js_v->u.object.values[1].value->u.array.values[0]->u.string.ptr
I've used them to reference to a string element inside an array:
{"t":"type","d":["element1","element2","element3"]}
In your case, I think you should to repeat the structure like this:
js_v->u.object.values[2].value->u.array.values[0]->u.object.values[0]->u.string.ptr
luck!

Resources