Python json_dumps in a single line without multiple { - python

I am exporting mysql table to a json file with
d = collections.OrderedDict()
d[i["parameter_name"]]=i["parameter_value"]#parameter_name
json_data.append(d)
result_json=json.dumps(json_data)
Currently the file is separate JSON records {}:
[{"Param1": "10.0000"}, {"Param2": "20.0000"}]
It should be one long JSON record in the format (only one set of {}):
[{"Param1": "10.0000", "Param2": "20.0000" ]
Any idea/ suggestion how to achieve this?

i'd do a dict comprehension
result_**string** = json.dumps( { key: value for key, value in *your_itereator* } )
string because you are using dumps
or maybe it looks like this, assuming you got the stuff in a dict called data (because you are using keys in your example)
{ x: data.get(x) for x in parameter_list }
or lazier
{ x: data.get(x) for x in data.keys() if "param" in x.lower() }
or to order them:
{ (z:=f"Param{x}"): data.get( z, "") for x in range(max_param) }

Related

Accessing Json object values with the Help of a dictionary

I've a huge json file which has a lot of nested key value pairs. So I thought I should save the keys as dictionary values and use that dictionary values as keys to access the values from the json file. Say for example:
json_obj = {
"calendar" :{
"day": {
"activities" : {
"morning:"walk"
}
}
}
}
so I thought to access the key morning value, instead of writing
json_obj['calendar']['day']['activities']['morning']
I should keep a dictionary which will contain the query parameters like
query_parameters = {
0 :[['calendar'],['day'],['activities'],['morning']]
}
And use this dictionary to query from the json object.
But
Here is my question?
Can I use this dictionary to write query or to access values from my json_obj without using any loops ?
say something like json_obj[query_parameters[0]] # this is not right syntax I know
Or do you have any suggestions when accessing these long key value pair from an object?
You can write a function like this
This function will return value if exist otherwise returns None
def fun(query, data):
if not query:
return data
if query[0][0] in data:
return fun(query[1:], data[query[0][0]])
print(fun(query_parameters[0], json_obj)) # walk

Read json key and value as a variables to pass to another function in python

I have a json config file like this
{
"sources":[
{
"name":"tbl1",
"var":"L100",
"query":"select c1,c2 from tbl1 where c1=L100"
},
{
"name":"tbl2",
"var":"M00",
"query":"select c1,c2 from tbl1 where c1=M00"
},
]
}
I would like to read name, var and query and send key and value to other python function for next processing.
Can anyone please how to write the script?
I have tried below code and could not to capture the values properly.
import json
with open('file.json', "r") as myfile:
json_data = json.load(myfile)
for e, v in json_data.items():
for key, val in v:
print(val)
Expected: Read the json data (name, var and query) value and pass to python function.
read json
capture values corresponds to first, second records, etc...
pyfun(name, var, query). In this function I am going to use these values for further procedure.
You can directly get the sources key then iterate with each dictionary and get the required keys
for x in json_data['sources']:
name, var, query = x['name'], x['var'], x['query']
# do something

Removing root node in json in Python

I have a json data stored in a variable.
Json Data:
{ "XYZ": { "abc":[{....}] } }
From above JSON Data, I should not have XYZ node. I need JSON Data as
{ "abc":[{....}] }
How can I remove using Python?
Thanks a lot!
You want to look up the dictionary via it's key ("XYZ") and assign it to a new variable:
data = request_data.get("XYZ")
this will return None if there is no "XYZ" key, but if you know the "XYZ" key is always going to be there you can lookup like so:
data = requests_data["XYZ"]

my loop is only printing the second part of the dictionary , i'm using json

import json
data ='''
{
"names": {"first_boy" : "khaled"},
"names": {"second_boy" : "waseem"}
}
'''
info = json.loads(data)
for line in info:
print(info["names"])
I expected it to print the first_boy and the second_boy dictionary ,but it's printing
{'second_boy': 'waseem'}
Dicts in python can only support one of the same key. Similarly, most implementations of JSON do not allow duplicate keys. The way python handles this, when using json.loads() (or anything else that constructs a dict) is to simply use the most recent definition of any given key.
In this case, {"second_boy":"waseem"} overwrites {"first_boy":"khaled"}.
The problem here is that the key "names" exists 2 times.
Maybe you can do this:
import json
data ='''
{
"names": {"first_boy" : "khaled",
"second_boy" : "waseem"}
}
'''
info = json.loads(data)
for key, value in info['names'].items():
print(key, value)

access nested data in json

I want to retrieve all the IP address range from Azure cloud from here
The data after conversion in json is in the following format:
{
"AzurePublicIpAddresses": {
"Region": [
{
...
"IpRange": [
{
"_Subnet": "40.69.96.0/19"
},
{
"_Subnet": "40.86.192.0/18"
}
],
"_Name": "canadaeast"
},
{
"IpRange": [
{
"_Subnet": "13.71.160.0/19"
},
{
"_Subnet": "13.88.224.0/19"
},
{
"_Subnet": "40.85.192.0/18"
}
],
"_Name": "canadacentral"
}
],
"_xmlns:xsd": "http://www.w3.org/2001/XMLSchema",
"_xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance"
}
}
I am unable to access IP ranges? through this code?
with open('AZURE_IP.json') as data_file:
data = json.load(data_file)
list_IPCIDR = []
for i in data["AzurePublicIpAddresses"]:
for ii in i["Region"]:
for j in ii["IpRange"]:
list_IPCIDR.append(i["_Subnet"])
sys.stdout=open("test2.txt","w")
data["AzurePublicIpAddresses"] is a dict. Iterating directly over a dict just gives you the the keys of that dict.
So
for i in data["AzurePublicIpAddresses"]:
print(i)
will print
Region
_xmlns:xsd
_xmlns:xsi
in some order.
You can get the Subnet IP ranges like this:
list_IPCIDR = []
for ipr in data["AzurePublicIpAddresses"]["Region"]:
for d in ipr["IpRange"]:
list_IPCIDR.append(d["_Subnet"])
print(list_IPCIDR)
output
['40.69.96.0/19', '40.86.192.0/18', '13.71.160.0/19', '13.88.224.0/19', '40.85.192.0/18']
This works because data["AzurePublicIpAddresses"]["Region"] is a list of dicts. Each of those dict (that are temporarily bound to the name ipr) contains a list of dicts associated with the "IpRange" key, so we need to iterate over those lists in the inner loop, and then extract the subnet strings from those inner dicts.
If you like you can do this in a list comprehension, butI advise splitting it up over several lines, eg:
list_IPCIDR = [d["_Subnet"]
for ipr in data["AzurePublicIpAddresses"]["Region"]
for d in ipr["IpRange"]]
It's often desirable to iterate over the (key, value) pairs of a dict. You can do that using the .items method (or .iteritems in Python 2). Eg,
list_IPCIDR = []
for key, val in data["AzurePublicIpAddresses"].items():
if key == "Region":
for dct in val:
for s in dct["IpRange"]:
list_IPCIDR.append(s["_Subnet"])
AzurePublicIpAddresses is a dictionary, so:
for i in data["AzurePublicIpAddresses"]:
Iterates through the keys (which are strings, in this case). I.e. you're trying to do "Region"["Region"], which is string slicing. Try something more like:
for i in data["AzurePublicIpAddresses"]:
for ii in data["Azure..."][i]:
# Use ii as it is the contents of the 'Region' attribute
if type(ii) == list: # Sometimes ii is a string, like at the end of your data.
list_IPCIDR.append(ii["IpRange"]["_Subnet"])

Categories

Resources