If key exists i json file - json

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'");
}

Related

How to convert key value text to json arrya format python

I have a use case where we have text file like key value format .
The file is not any of the fixed format but created like key value .
We need to create JSON out of that file .
I am able to create JSON but when text format has array like structure it creates just Key value json not the array json structure .
This is my Input .
[DOCUMENT]
Headline=This is Headline
MainLanguage=EN
DocType.MxpCode=1000
Subject[0].MxpCode=BUSNES
Subject[1].MxpCode=CONS
Subject[2].MxpCode=ECOF
Author[0].MxpCode=6VL6
Industry[0].CtbCode=53
Industry[1].CtbCode=5340
Industry[2].CtbCode=534030
Industry[3].CtbCode=53403050
Symbol[0].Name=EXPE.OQ
Symbol[1].Name=ABNB.OQ
WorldReg[0].CtbCode=G4
Country[0].CtbCode=G26
Country[1].CtbCode=G2V
[ENDOFFILE]
Exiting code to create json is below
with open("file1.csv") as f:
lines = f.readlines()
data = {}
for line in lines:
parts = line.split('=')
if len(parts) == 2:
data[parts[0].strip()] = parts[1].strip()
print(json.dumps(data, indent=' '))
The current output is below
{
"Headline": "This is Headline",
"MainLanguage": "EN",
"DocType.MxpCode": "1000",
"Subject[0].MxpCode": "BUSNES",
"Subject[1].MxpCode": "CONS",
"Subject[2].MxpCode": "ECOF",
"Author[0].MxpCode": "6VL6",
"Industry[0].CtbCode": "53",
"Industry[1].CtbCode": "5340",
"Industry[2].CtbCode": "534030",
"Industry[3].CtbCode": "53403050",
"Symbol[0].Name": "EXPE.OQ",
"Symbol[1].Name": "ABNB.OQ",
"WorldReg[0].CtbCode": "G4",
"Country[0].CtbCode": "G26",
"Country[1].CtbCode": "G2V"
}
Expected out is is something like below
For the Subject key and like wise for others also
{
"subject": [
{
"mxcode": 123
},
{
"mxcode": 123
},
{
"mxcode": 123
}
]
}
Like wise for Industry and Symbol and Country.
so the idea is when we have position in the text file it should be treated as array in the json output .
Use one more loop as it is nested. Use for loop from where subject starts. try it that way.

Append in nested array JSON object in oracle

I have JSON document column in one of the table and its structure is like:-
{
"root":[{"MCR":"MCR_1",
"MCR_COLUMNS":{
"MCR_COLUMN_1":"ABC1",
"MCR_COLUMN_2":"ABC2"
}
},
{"MCR":"MCR_2",
"MCR_COLUMNS":{
"MCR_COLUMN_1":"XYZ1",
"MCR_COLUMN_2":"XYZ2"
}
}
]
}
Now I want to write a merge statement to merge in this document to manage two cases
CASE-1) If MCR value is already present in document, then directly append MCR_COLUMN_x and its value to JSON object of its MCR_COLUMNS. eg. I want to append
{"MCR":"MCR_1",
"MCR_COLUMNS":{
"MCR_COLUMN_3":"ABC3"
}
}
so, the updated document should be
{
"root":[{"MCR":"MCR_1",
"MCR_COLUMNS":{
"MCR_COLUMN_1":"ABC1",
"MCR_COLUMN_2":"ABC2",
"MCR_COLUMN_3":"ABC3"
}
},
{"MCR":"MCR_2",
"MCR_COLUMNS":{
"MCR_COLUMN_1":"XYZ1",
"MCR_COLUMN_2":"XYZ2"
}
}
]
}
CASE-2) If MCR value does not exist then it appends a new JSON object into the root array. for eg: if i want to append
{"MCR":"MCR_3",
"MCR_COLUMNS":{
"MCR_COLUMN_1":"UVW1",
"MCR_COLUMN_2":"UVW2"
}
}
then updated document should be
{
"root":[{"MCR":"MCR_1",
"MCR_COLUMNS":{
"MCR_COLUMN_1":"ABC1",
"MCR_COLUMN_2":"ABC2"
}
},
{"MCR":"MCR_2",
"MCR_COLUMNS":{
"MCR_COLUMN_1":"XYZ1",
"MCR_COLUMN_2":"XYZ2"
}
},
{"MCR":"MCR_3",
"MCR_COLUMNS":{
"MCR_COLUMN_1":"UVW1",
"MCR_COLUMN_2":"UVW2"
}
}
]
}
I had tried JSON_mergepatch and JSON_Transform but case-1 I'm not able to achieve. And since I'll not have before-hand knowledge whether MCR is already present or not, I just can not only right solution for case-2.
Any help or suggestion will be very much appreciated.
To check if the MCR value exists:
WHERE json_exists(json_value, '$?(#.root[*].MCR == "MCR_1")')
To add an item to MCR_COLUMNS
update test_js
set json_value = json_transform(
json_value,
INSERT '$.root.MCR_COLUMNS.MCR_COLUMN_3' = 'ABC3'
)
where json_exists(json_value, '$?(#.root[*].MCR == "MCR_1")')
;
To add an item to root array:
update test_js
set json_value = json_transform(
json_value,
APPEND '$.root' = '{"MCR":"MCR_3", "MCR_COLUMNS":{ "MCR_COLUMN_1":"UVW1", "MCR_COLUMN_2":"UVW2" } }' FORMAT JSON
)
where not json_exists(json_value, '$?(#.root[*].MCR == "MCR_3")')
;
In addition to #p3consulting's answer, to insert into a particular array element only(here in this case 'MCR_1') further conditions can be applied to INSERT.
update test_js
set json_value = json_transform( json_value, INSERT '$.root[*]?(#.MCR=="MCR_1").MCR_COLUMNS.MCR_COLUMN_4' = 'ABC4') )
where json_exists(json_value, '$?(#.root[*].MCR == "MCR_1")') ;

reorder json object nested properties by key

{
"color_group_01": {
"blue_50": "#4080fb",
"blue_40": "#6fa1fc",
"blue_30": "#9dc2fd",
"blue_20": "#cadefe",
"blue_10": "#ebf4ff",
"blue_100": "#011338",
"blue_90": "#011d5f",
"blue_80": "#022b8f",
"blue_70": "#053fc4",
"blue_60": "#165cfa"
},
"color_group_02": {
"green_90": "#022d0d",
"green_80": "#044317",
"green_70": "#0e6027",
"green_100": "#071908",
"green_60": "#198038",
"green_50": "#24a148",
"green_40": "#42be65",
"green_30": "#6fdc8c",
"green_20": "#a7f0ba",
"green_10": "#defbe6"
}
}
I have a JSON file that is generated as above. It has 12 "color_group_" objects.
What I want to do is re order the properties within each group by key to go from 10-100. And also keep the "color_group_" in order 01-12. Resulting like below:
{
"color_group_01": {
"blue_10": "#ebf4ff",
"blue_20": "#cadefe",
"blue_30": "#9dc2fd",
"blue_40": "#6fa1fc",
"blue_50": "#4080fb",
"blue_60": "#165cfa",
"blue_70": "#053fc4",
"blue_80": "#022b8f",
"blue_90": "#011d5f",
"blue_100": "#011338"
},
"color_group_02": {
"green_10": "#defbe6",
etc...
}
}
I am struggling how to do this? Could some please help? No jQuery solutions please :)
Thanks in advance
First you need to load your JSON into a javascript object using JSON.parse(). However your objects don't really know a sorting of their keys, instead you can extract the keys of your object and sort them accordingly
const keysArray = Object.keys(yourObject).sort((a, b) => /* your sort function here */);
Then you can loop through this keysArray, which is now all your keys sorted and access your object from there
keysArray.forEach(key => console.log(yourObject[key]));

Parsing json : Test is json key existing

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

Retrieving dictionary keys with pre-fixed parent keys using python

I am trying to list all keys with parent keys from a dictionary using python 3. How can I achieve this goal?
Here is so far I did using a recursive function (so that I can use this with any depth of dictionaries).
Here, if I do not use header_prefix, I get all the keys without parent keys. However, when I use header_prefix, it keeps adding parent keys incorrectly to the keys. Basically, I cannot reset header_prefix in the appropriate location.
from pprint import pprint
#%%
data = {
"AWSTemplateFormatVersion": "2010-09-09" ,
"Description": "Stack for MyProject 01",
"Resources": {
"elb01": {
"Type": "AWS::ElasticLoadBalancing::LoadBalancer",
"Properties": {
"CrossZone" : "false",
"HealthCheck" : {
"Target" : "TCP:80",
"Interval" : "20"
},
"ConnectionSettings": {
"IdleTimeout": "120"
}
}
},
"lc01": {
"Type": "AWS::AutoScaling::LaunchConfiguration" ,
"Properties": {
"ImageId" : "ami-01010105" ,
"InstanceType" : "t2.medium"
}
},
"asg01": {
"Type" : "AWS::AutoScaling::AutoScalingGroup",
"Properties" : {
"HealthCheckGracePeriod" : 300,
"HealthCheckType" : "EC2"
}
}
}
}
pprint(data)
#%%
def get_headers(json_data, headers, header_prefix):
for key, value in json_data.items():
if type(value) == dict:
header_prefix = header_prefix + key + '.'
get_headers(value,headers,header_prefix)
else:
headers.append(header_prefix+key)
return(headers)
#%%
header_list = []
prefix = ''
data_headers = get_headers(data, header_list, prefix)
pprint(data_headers)
From the above code, I get the following output:
['AWSTemplateFormatVersion',
'Description',
'Resources.elb01.Type',
'Resources.elb01.Properties.CrossZone',
'Resources.elb01.Properties.HealthCheck.Target',
'Resources.elb01.Properties.HealthCheck.Interval',
'Resources.elb01.Properties.HealthCheck.ConnectionSettings.IdleTimeout',
'Resources.elb01.lc01.Type',
'Resources.elb01.lc01.Properties.ImageId',
'Resources.elb01.lc01.Properties.InstanceType',
'Resources.elb01.lc01.asg01.Type',
'Resources.elb01.lc01.asg01.Properties.HealthCheckGracePeriod',
'Resources.elb01.lc01.asg01.Properties.HealthCheckType']
My expected output is like below:
['AWSTemplateFormatVersion',
'Description',
'Resources.elb01.Type',
'Resources.elb01.Properties.CrossZone',
'Resources.elb01.Properties.HealthCheck.Target',
'Resources.elb01.Properties.HealthCheck.Interval',
'Resources.elb01.Properties.ConnectionSettings.IdleTimeout',
'Resources.lc01.Type',
'Resources.lc01.Properties.ImageId',
'Resources.lc01.Properties.InstanceType',
'Resources.asg01.Type',
'Resources.asg01.Properties.HealthCheckGracePeriod',
'Resources.asg01.Properties.HealthCheckType']
It seems to be a scoping issue. When you modify header_prefix inside the if statement, it modifies it in the function scope and so for all iterations of the loop, leading to the incorrect version being passed to get_headers in later iterations of the loop
In short:
Change
header_prefix = header_prefix + key + '.'
get_headers(value,headers,header_prefix)
To
pfx = header_prefix + key + '.'
get_headers(value,headers,pfx)
This way a new local variable will be created and passed, rather than the header_prefix being updated within the function scope.
(any variable name that's not used within the get_headers function will do