Parsing json : Test is json key existing - json

I'm request with API REST a JIRA filter since Excel and I return my result in a json object.
I'm parsing this object and I Try to show my result (in a msgbox for now) but I have a problem when the json Key doesn't exist !
A extract of my json :
{
"expand":"schema,names",
"startAt":0,
"maxResults":500,
"total":2,
"issues":[
{
"expand":"operations,versionedRepresentations,editmeta,changelog,renderedFields",
"id":"00001",
"fields":{
"components":[
{
"id":"01",
"name":"component_1"
},
{
"id":"02",
"name":"component_02"
}
]
}
},
{
"expand":"operations,versionedRepresentations,editmeta,changelog,renderedFields",
"id":"00002",
"fields":{
"components":[
]
}
},
]
}
As you cans see, in my first issue (id 00001) I have a 2 components key but in my second issus (id 0002) I don't have component key, because this fields is empty in JIRA for this issue.
So, a part of my code to show my result :
For Each Item In jsonObject("issues")
issueId = Item("id")
compoId1 = Item("fields")("components")(1)("id")
compoId2 = Item("fields")("components")(2)("id")
i = i + 1
'PRINT_OF_MY_RESULT
Next
My problem :
If my issue (00001) has a "component" value, it's OK and I can return my result but ... if my issus (00002) hasn't a result, my code failled to define compoId ... and my code crash.
Did you have a simple solution ? I try somethings with Exists, isEmpty, etc etc ... but nothing concluent for me :(

You can modify your solution some what like this,
For Each Item In jsonObject("issues")
issueId = Item("id")
For Each componentItem In jsonObject(Item("fields")("components"))
If componentItem("id")==1 then
compoId1 = componentItem("id")
EndIf
If componentItem("id")==1 then
compoId2 = componentItem("id")
EndIf
Next
i = i + 1
'PRINT_OF_MY_RESULT
Next

Related

If key exists i json file

Loading a normal json file. How do I find if this key exists in json string
-> jsonstreng["kjoretoydataListe"][0]["kjennemerke"][1]["kjennemerke"]
Doing this of course without breaking my program if it's not.
jsonstreng = {
"kjoretoydataListe":
[
{
"kjoretoyId": {"kjennemerke":"EK 17058","understellsnummer":"5YJXCCE29GF009633"},
"forstegangsregistrering": {"registrertForstegangNorgeDato":"2016-09-07"},
"kjennemerke": [
{"fomTidspunkt":"2016-09-07T00:00:00+02:00","kjennemerke":"EK 17058","kjennemerkekategori":"KJORETOY",
"kjennemerketype":{"kodeBeskrivelse":"Sorte tegn p- hvit bunn","kodeNavn":"Ordin-re kjennemerker","kodeVerdi":"ORDINART","tidligereKodeVerdi":[]}},{"fomTidspunkt":"2022-08-19T17:04:04.334+02:00","kjennemerke":"GTD","kjennemerkekategori":"PERSONLIG"}
]
}
]
}
def checkIfKeyExistsInDict(in_dict, i_key):
if(isinstance(in_dict, dict)):
if(i_key in in_dict):
print(i_key + " found in: " + str(in_dict))
print()
for j_key in in_dict:
checkIfKeyExistsInDict(in_dict[j_key], i_key)
elif(isinstance(in_dict, list)):
for j_key in range(len(in_dict)):
checkIfKeyExistsInDict(in_dict[j_key], i_key)
checkIfKeyExistsInDict(jsonstreng, "kjennemerke")
If you are using Python, the way to find if key (let's say "kjennemerke") is present in a JSON object (let's say "jsonstreng") is:
if ("kjennemerke" in jsonstreng):
"""If body goes here"""
pass
Just for info, if you are trying to do the same in thing in JavaScript the if condition above will look like as shown below:
let jsonstreng_with_key = {
"kjennemerke": 1
}
let jsonstreng_without_key = {} // Empty object
if(jsonstreng_with_key.hasOwnProperty('kjennemerke')){
console.log("jsonstreng_with_key has key 'kjennemerke'");
} else {
console.log("jsonstreng_with_key does not have key 'kjennemerke'");
}
if(jsonstreng_without_key.hasOwnProperty("kjennemerke")){
console.log("jsonstreng_without_key has key 'kjennemerke'");
} else {
console.log("jsonstreng_without_key does not have key 'kjennemerke'");
}

How to check a value matches with another correpsonding value in a json response

What is the most dynamic way of checking each instance of a json response value matches another json response value within a script assertion?
What I mean is lets say I have the following response below:
{
"xxx": [{
"roomInformation": [{
"xxx": xxx
}],
"totalPrice": xxx
},
{
"roomInformation": [{
xxx: xxx
}],
"totalPrice": xxx
}
]
}
I want to check that the first room price to match with the first totalPrice and the second roomPrice to match with the second totalPrice. It has to be dynamic as I may get many different instances of this so I can't simply just look through the json with [0] and [1]. Virtually check each roomPrice matches with its corresponding totalPrice.
Thanks
So given the Json as a variable:
def jsonTxt = '''{
"hotels": [{
"roomInformation": [{
"roomPrice": 618.4
}],
"totalPrice": 618.4
},
{
"roomInformation": [{
"roomPrice": 679.79
}],
"totalPrice": 679.79
}
]
}'''
We can then use the following script:
import groovy.json.*
new JsonSlurper().parseText(jsonTxt).hotels.each { hotel ->
assert hotel.roomInformation.roomPrice.sum() == hotel.totalPrice
}
As you can see, I'm using sum to add all the roomInformation.roomPrice values together. In your example, you only have one price, so this will be fine.. And it will also cover the case where you have multiple rooms adding up to make the total
Here is the script assertion to check each roomPrice is matching or not with totalPrice.
EDIT: based on OP's full response provided here
Script Assertion:
//Check if the response is not empty
assert context.response, "Response is empty or null"
def json = new groovy.json.JsonSlurper().parseText(context.response)
def sb = new StringBuffer()
json.regions.each { region ->
region.hotels.each { hotel ->
(hotel?.totalPrice == hotel?.roomInformation[0]?.roomPrice) ?: sb.append("Room price ${hotel?.roomInformation[0]?.roomPrice} is not matching with total price ${hotel.totalPrice}")
}
}
if (sb.toString()) {
throw new Error(sb.toString())
} else { log.info 'Prices match' }

How to send multiple documents using RMongo

I am following the conventions from http://docs.mongodb.org/manual/reference/method/db.collection.insert/
to send a batch of multiple documents in one call of RMongo::dbInsertDocument.
data=data.frame(A=c(1,2),B=c(3,4))
L=lapply(split(data,rownames(data)),as.list)
names(L)=NULL
dataJSON = toJSON(L)
cat(dataJSON)
which gives the following result:
[
{
"A":1,
"B":3
},
{
"A":2,
"B":4
}
]
Then
dbInsertDocument(rmongo.object=myRmongo.object, collection=myCollection, doc=dataJSON)
returns the following error:
Error in ls(envir = envir, all.names = private) :
invalid 'envir' argument
Note that if I replace
L = L[[1]
Then
cat(dataJSON)
gives the following result:
{
"A":1,
"B":3
}
and the same call to dbInsertDocument works with no error (and the data is indeed sent to the database)
Has anyone figured this out? I would really like a better way to do this, but for now am just looping over the list (not ideal)
data=data.frame(A=c(1,2),B=c(3,4))
L=lapply(split(data,rownames(data)),as.list)
names(L)=NULL
for (i in 1:NROW(L)) {
dataJSON = toJSON(L[[i]])
output <- dbInsertDocument(mongo, "test_data7", dataJSON)
}

simple json parsing with asp Xtreme

Just confused with one little thing.
I am currently getting { "data": [ { "response": "true" } ] } with the following code.
But I simple want to get { "response": "true" }.
I tried every way I can but I kept failing.
I will appreciate a lot if you can help me with it.
Set Dataset = JSON.parse("{ ""data"": [] }")
Set Record = JSON.parse("{}")
Record.set "response", "true"
Dataset.data.push(Record)
Set Record = nothing
Data = JSON.stringify(Dataset, null, 2)
Set Record = JSON.parse("{}")
Record.set "response", "true"
Data = JSON.stringify(Record, null, 2)
I assume that JSONObject.data.push adds the record to an unnamed array.

What is "compressed JSON"?

I see a lot of references to "compressed JSON" when it comes to different serialization formats. What exactly is it? Is it just gzipped JSON or something else?
Compressed JSON removes the key:value pair of json's encoding to store keys and values in seperate parallel arrays:
// uncompressed
JSON = {
data : [
{ field1 : 'data1', field2 : 'data2', field3 : 'data3' },
{ field1 : 'data4', field2 : 'data5', field3 : 'data6' },
.....
]
};
//compressed
JSON = {
data : [ 'data1','data2','data3','data4','data5','data6' ],
keys : [ 'field1', 'field2', 'field3' ]
};
This method of usage i found here
Content from link (http://www.nwhite.net/?p=242)
rarely find myself in a place where I am writing javascript applications that use AJAX in its pure form. I have long abandoned the ‘X’ and replaced it with ‘J’ (JSON). When working with Javascript, it just makes sense to return JSON. Smaller footprint, easier parsing and an easier structure are all advantages I have gained since using JSON.
In a recent project I found myself unhappy with the large size of my result sets. The data I was returning was tabular data, in the form of objects for each row. I was returning a result set of 50, with 19 fields each. What I realized is if I augment my result set I could get a form of compression.
// uncompressed
JSON = {
data : [
{ field1 : 'data1', field2 : 'data2', field3 : 'data3' },
{ field1 : 'data4', field2 : 'data5', field3 : 'data6' },
.....
]
};
//compressed
JSON = {
data : [ 'data1','data2','data3','data4','data5','data6' ],
keys : [ 'field1', 'field2', 'field3' ]
};
I merged all my values into a single array and store all my fields in a separate array. Returning a key value pair for each result cost me 8800 byte (8.6kb). Ripping the fields out and putting them in a separate array cost me 186 bytes. Total savings 8.4kb.
Now I have a much more compressed JSON file, but the structure is different and now harder to work with. So I implement a solution in Mootools to make the decompression transparent.
Request.JSON.extend({
options : {
inflate : []
}
});
Request.JSON.implement({
success : function(text){
this.response.json = JSON.decode(text, this.options.secure);
if(this.options.inflate.length){
this.options.inflate.each(function(rule){
var ret = ($defined(rule.store)) ? this.response.json[rule.store] : this.response.json[rule.data];
ret = this.expandData(this.response.json[rule.data], this.response.json[rule.keys]);
},this);
}
this.onSuccess(this.response.json, text);
},
expandData : function(data,keys){
var arr = [];
var len = data.length; var klen = keys.length;
var start = 0; var stop = klen;
while(stop < len){
arr.push( data.slice(start,stop).associate(keys) );
start = stop; stop += klen;
}
return arr;
}
});
Request.JSON now has an inflate option. You can inflate multiple segments of your JSON object if you so desire.
Usage:
new Request.JSON({
url : 'url',
inflate : [{ 'keys' : 'fields', 'data' : 'data' }]
onComplete : function(json){}
});
Pass as many inflate objects as you like to the option inflate array. It has an optional property called ’store’ If set the inflated data set will be stored in that key instead.
The ‘keys’ and ‘fields’ expect strings to match a location in the root of your JSON object.
Based in Paniyar's answer, we can convert a List of Objects in "compressed" Json format using C# like this:
var JsonString = serializer.Serialize(
new
{
cols = new[] { "field1", "field2", "field3"},
items = data.Select(x => new object[] {x.field1, x.field2, x.field3})
});
I used an array of object because the fields can be int, bool, string...
More Reduction:
If the field is repeated very often and it is a string type, you can get compressed a little be more if you add a distinct list of that field... for instance, a field name job position, city, etc are excellent candidate for this. You can add a distinct list of this items and in each item change the value for a reference number. That will make your Json more lite.
Compressed:
[["KeyA", "KeyB", "KeyC", "KeyD", "KeyE", "KeyF"],
["ValA1", "ValB1", "ValC1", "ValD1", "ValE1", "ValF1"],
["ValA2", "ValB2", "ValC2", "ValD2", "ValE2", "ValF2"],
["ValA3", "ValB3", "ValC3", "ValD3", "ValE3", "ValF3"],
["ValA4", "ValB4", "ValC4", "ValD4", "ValE4", "ValF4"]]
Uncompressed:
[{KeyA: "ValA1", KeyB: "ValB1", KeyC: "ValC1", KeyD: "ValD1", KeyE: "ValE1", KeyF: "ValF1"},
{KeyA: "ValA2", KeyB: "ValB2", KeyC: "ValC2", KeyD: "ValD2", KeyE: "ValE2", KeyF: "ValF2"},
{KeyA: "ValA3", KeyB: "ValB3", KeyC: "ValC3", KeyD: "ValD3", KeyE: "ValE3", KeyF: "ValF3"},
{KeyA: "ValA4", KeyB: "ValB4", KeyC: "ValC4", KeyD: "ValD4", KeyE: "ValE4", KeyF: "ValF4"}]
The most likely answer is that it really is just gzipped JSON. There is no other standard meaning to this phrase.
Re-organizing a homogenous array of JSON objects into a pair of arrays is a very useful technique to make the payload smaller and to speed up encoding and decoding, it is not commonly called "compressed JSON". I haven't run across it ever in open source or any open API, but we use this technique internally and call it "jsontable".