How to remove bracket from JSON in Flask - python

I want to remove one fo them bracket from JSON in Flask. I want to get result from database and convert to JSON.
i=0
a = []
for food in sorted_similar_food:
if i==0:
i = i+1
else:
name = get_title_from_index(food[0])
name = str(name)
db_cursor.execute("SELECT * FROM recipe where name = " + "'" + name + "'")
r = [dict((db_cursor.description[i][0], value)
for i, value in enumerate(row)) for row in db_cursor.fetchall()]
a.append( r)
return jsonify({'cursor': a})
AND my result JSON
{ "cursor": [
[
{
"id": 3,
"image": "https://firebasestorage.googleapis.com/v0/b/cricket-17449.appspot.com/o/manti.jpg?alt=media&token=d11a65ec-6486-4b24-a54a-2840ce4fdc",
"ind": "kiyma yumurta sogan un",
"name": "manti",
"recip": "Ge"
}
],
....
]}
There are two brackets. I want to one of them. I should remove one of them.

You start with an empty list a=[]. Inside your loop, you append a list of DB results (r is another list). What you want to do is a.extend(r). That way the elements inside r are appended to a and you end up with just the a list.

Related

Store results of nested for loop as single concatenated string

I'm trying to store the values of the function below to a single string that I can input into a query leveraging an F-string. The output looks correct but is really just a few separated print statements.
How can I store the output of the below to a single string?
import pandas as pd
view_dict = [{'id':'168058','viewtime_min':'2023-01-26 21:00:59.435 -0600','viewtime_max':'2023-01-26 21:59:59.435 -0600'},
{'id':'167268','viewtime_min':'2023-01-26 21:59:59.435 -0600','viewtime_max':'2023-01-26 21:59:59.435 -0600'},
{'id':'167268','viewtime_min':'2023-01-26 21:59:59.435 -0600','viewtime_max':'2023-01-26 21:59:59.435 -0600'}]
def get_where_clause(view_dictionary: dict):
where_clause = " "
for index in range(len(view_dictionary)):
if index != max(range(len(view_dictionary))):
print(f'''(b.id = {view_dictionary[index]['id']}
and b.viewed_at between coalesce({view_dictionary[index]['viewtime_min']},published_at) and {view_dictionary[index]['viewtime_max']})
or''')
else:
print(f'''(b.id = {view_dictionary[index]['id']}
and b.viewed_at between coalesce({view_dictionary[index]['viewtime_min']},published_at) and {view_dictionary[index]['viewtime_max']})''')
x = get_where_clause(view_dict)
x
I'm expecting this to store to a value but when accessing the value nothing is stored.
You aren't actually returning or storing anything, print simply writes to the console. Ideally, you'd collect these into something like a list to be returned, which you can then use str.join to concatenate:
view_dict = [{'id':'168058','viewtime_min':'2023-01-26 21:00:59.435 -0600','viewtime_max':'2023-01-26 21:59:59.435 -0600'},
{'id':'167268','viewtime_min':'2023-01-26 21:59:59.435 -0600','viewtime_max':'2023-01-26 21:59:59.435 -0600'},
{'id':'167268','viewtime_min':'2023-01-26 21:59:59.435 -0600','viewtime_max':'2023-01-26 21:59:59.435 -0600'}]
def get_where_clause(view_dictionary: dict):
# I've changed this to a list
where_clause = []
for index in range(len(view_dictionary)):
if index != max(range(len(view_dictionary))):
where_clause.append(f'''(b.id = {view_dictionary[index]['id']}
and b.viewed_at between coalesce({view_dictionary[index]['viewtime_min']},published_at) and {view_dictionary[index]['viewtime_max']})
or''')
else:
where_clause.append(f'''(b.id = {view_dictionary[index]['id']}
and b.viewed_at between coalesce({view_dictionary[index]['viewtime_min']},published_at) and {view_dictionary[index]['viewtime_max']})''')
# join together here
return ' '.join(where_clause)
x = get_where_clause(view_dict)
print(x)
I know it isn't asked for, but this could be cleaned up a little more with some basic iteration techniques:
def get_where_clause(view_dictionary: list):
# I've changed this to a list
where_clause = []
# grab the last element and iterate over a slice
# rather than checking an index
last = view_dictionary[-1]
# iterate over the views directly, don't use an index
for item in view_dictionary[:-1]:
where_clause.append(f'''(b.id = {item['id']}
and b.viewed_at between coalesce({item['viewtime_min']},published_at) and {item['viewtime_max']})
or''')
where_clause.append(f'''(b.id = {last['id']}
and b.viewed_at between coalesce({last['viewtime_min']},published_at) and {last['viewtime_max']})''')
# join together here
return ' '.join(where_clause)
And to simplify formatting, you can indent a single string by using parentheses:
for item in view_dictionary:
where_clause.append(
f"(b.id = {item['id']} "
"and b.viewed_at between "
f"coalesce({item['viewtime_min']},published_at) "
f"and {item['viewtime_max']})"
)
# rather than checking for first/last, you can join on
# 'or'
return ' or '.join(where_clause)
The print command just writes the text to your screen, it does not return a value. Your function needs to return a value for it to be "storable" in a variable.
I rewrote, formatted and commented your code, it now returns a string containing the where clause:
view_dict = [
{
"id": "168058",
"viewtime_min": "2023-01-26 21:00:59.435 -0600",
"viewtime_max": "2023-01-26 21:59:59.435 -0600",
},
{
"id": "167268",
"viewtime_min": "2023-01-26 21:59:59.435 -0600",
"viewtime_max": "2023-01-26 21:59:59.435 -0600",
},
{
"id": "167268",
"viewtime_min": "2023-01-26 21:59:59.435 -0600",
"viewtime_max": "2023-01-26 21:59:59.435 -0600",
},
]
def get_where_clause(view_dictionary: list[dict]) -> str:
# This is where all the outputs will be stored
outputs = []
# Loop over the view_dictionary, which is actually a list of dicts
for vd in view_dictionary:
# Just for readability: get the relevant parts out of each dict
bid = vd['id']
tmin = vd['viewtime_min']
tmax = vd['viewtime_max']
# Place everything in an f-string
output = f"(b.id = {bid} and b.viewed_at between coalesce('{tmin}',published_at) and '{tmax}') or"
# Print, just for fun, you won't use this output
print(output)
# Place every output in the outputs list
outputs.append(output)
# Create the actual WHERE clause by concatenating all outputs into a single string
# the [:-3] makes sure the last 'or' keyword is removed
where_clause = " ".join(outputs)[:-3]
return where_clause
x = get_where_clause(view_dict)

Getting AttributeError parsing JSON data

I'm getting a JSON data from server and I need to parse it separately, when I do this with SimpleNamespace I get the problem. How can I parse this data?
Example Data:
{
"version":"1.0",
"packageName":"com.some.thing",
"eventTimeMillis":"1503349566168",
"subscriptionNotification":
{
"version":"1.0",
"notificationType":4,
"purchaseToken":"PURCHASE_TOKEN",
"subscriptionId":"my.sku"
}
}
My Code:
import json
from types import SimpleNamespace
def callback(message):
x = json.loads(message.data, object_hook=lambda d: SimpleNamespace(**d))
print("Version: " + x.version)
print("Package Name: " + x.packageName)
print("Time Milis: " + x.eventTimeMillis)
print("Token: " + x.subscriptionNotification.purchaseToken)
print("Product: " + x.subscriptionNotification.subscriptionId)
print("Type: " + str(x.subscriptionNotification.notificationType))
Error:
AttributeError: 'types.SimpleNamespace' object has no attribute 'subscriptionNotification'
In this example, we start with a dictionary. From then on there's very little code and the whole thing becomes "table driven". For example, if your dictionary structure changes such that you add a new key to the top level then you just need to make a corresponding change to the L1 table. Hopefully this will give you some ideas on how to proceed:
D = {
"version": "1.0",
"packageName": "com.some.thing",
"eventTimeMillis": "1503349566168",
"subscriptionNotification":
{
"version": "1.0",
"notificationType": 4,
"purchaseToken": "PURCHASE_TOKEN",
"subscriptionId": "my.sku"
}
}
def doPrint(d, L):
if d:
for _l in L:
print(f'{_l[0]}: {d.get(_l[1], "n/a")}')
L1 = [['Version', 'version'],
['Package Name', 'packageName'],
['Time Millis', 'eventTimeMillis']
]
L2 = [['Token', 'purchaseToken'],
['Product', 'subscriptionId'],
['Type', 'notificationType']
]
doPrint(D, L1)
doPrint(D.get('subscriptionNotification', None), L2)

Bitcoin Transaction Mapping Throws KeyError

I have the following piece of code, which seems to run until line 36 recipientlist.append(target["addr"]) and then throws the error KeyError: 'addr'
However 'addr' seems to be in the data so not sure what the issue is
Can someone please help?
import json
import requests
z = 0
i = 0
firstpart = "https://blockchain.info/rawaddr/"
initialinput = '3PaGEcGDjPsNQHAQ4pTmjQuLXWoEwvnr11'
initialreq = firstpart + initialinput
firstjson = (requests.get(initialreq)).json()
graphvizlines = []
addresslist = []
usedaddresslist = []
addresslist.append(initialinput)
usedaddresslist.append(initialinput)
while i < 6:
if z is 1:
initialreq = firstpart + addresslist[i]
firstjson = (requests.get(initialreq)).json()
for transaction in firstjson["txs"]:
payerlist = []
recipientlist = []
print("\n" + transaction["hash"])
for item in transaction["inputs"]:
payerlist.append(item["prev_out"]["addr"])
if item["prev_out"]["addr"] not in addresslist:
addresslist.append(item["prev_out"]["addr"])
for target in transaction["out"]:
recipientlist.append(target["addr"])
if target["addr"] not in addresslist:
addresslist.append(target["addr"])
for payer in payerlist:
for recipient in recipientlist:
a = '"' + payer + '"' + " -> " + '"' + recipient + '"' + ";"
if a not in graphvizlines:
graphvizlines.append(a)
i = i + 1
z = 1
for t in graphvizlines:
print(t)
While addr is in your data, it's not in every inputs element. Check the very last element in txs, you'll see that inputs is:
"inputs": [
{
"sequence": 0,
"witness": "304402203f872bfd7093fcdad6a3735cbd76f276279890b0304e6f23f54c51388cc2a84402203731d7a7f71265f072f6792c8f4d2e805ff8f86bbfbd0b48a187d573c051593001",
"prev_out": {
"spent": true,
"spending_outpoints": [
{
"tx_index": 0,
"n": 0
}
],
"tx_index": 0,
"type": 0,
"value": 1880609,
"n": 1,
"script": "0014292738ed3f9466f8eedd8c49e5bb013088a7052b"
},
"script": ""
}
],
This element lacks the presence of prev_out.addr.
You will need to first check if the addr element exists or wrap your loop in a try/except.
for transaction in firstjson['txs']:
...
for item in transaction['inputs']:
address = item.get('prev_out').get('addr')
if(address == None):
continue
payerlist.append(address)
...
The above would still fail if prev_out didn't exist, so you should confirm what will be in the result and what might be.

Multiple identical keys from Python dict to JSON

I am trying to create JSON object in Python, and it works just fine despite the fact that I can't get multiple keys with the same name - but I need to do it.
Here's a function:
findings = AutoTree()
findings['report']['numberOfConditions'] = num_cond
if r == 'Mammography':
f_temp = df['Relevant findings'].values.tolist()[0:8]
f_list = [x for i, x in enumerate(f_temp) if i == f_temp.index(x)]
f_num_total = len(f_list)
f_rand = random.randrange(1, f_num_total + 1)
iter_params_mass = ['shape', 'margin', 'density']
for i in range(num_cond):
br = get_birad(row, 2, 7)
cond = camelCase(get_cond_name())
findings[cond]['biRad'] = br
for k in range(f_rand + 1):
f = camelCase(random.choice(f_list))
#f = 'mass'
if f == 'mass':
rep_temp = create_rep(iter_params_mass, row, f, r)
findings[cond][f] = rep_temp
"""I also have a lot elif conditions, and it just grabs parameters."""
report = json.dumps(findings)
print(report)
Output:
{
"report":{
"id":85,
"name":"Lydia",
"age":39,
"relevantModality":"Mammography",
"numberOfConditions":2
},
"ductEctasia":{
"biRad":"birad[1]",
"calcifications":[
{
"typicallyBenign":"Vascular",
"suspiciousMorphology":"Coarse heterogeneous",
"distribution":"Diffuse"
}
],
"lymphNodes":[
{
"lymphNodes":"Lymph nodes \u2013 axillary"
}
]
}
}
And I want to have multiple "lymphNodes" and "calcifications" objects. Is it possible? Maybe, you can suggest another way to create JSON object, not nested dictionaries? The problem is that I need to create object respectively to random parameter chosen from the database.

loop is not working when I try to read a Json file and a text file with python

I have a json file with objects and a text file with several groups (Each group have 5 numbers and I have them in a list this way: the first number of each group are in list 1, the second number of each group, are in list 2, etc). I basically have to match each object of the json with each group I created. The problem is that Im getting as result the last element from the Json. The groups from the text file are created in the correct way.
This is my code:
import json
NUM_LIST = 5
index = 0
def report(a, b, c, d, e, index):
json_file = 'json_global.json'
json_data = open(json_file)
data = json.load(json_data)
i = 0
index = 0
item = 0
cmd = " "
ind = 0
for node in data:
for i in range(0, 5):
item = data[i]['item']
cmd = data[i]['command']
index+= 1
print item, cmd, a, b, c, d, e
f = open("Output.txt", "r")
lines = [line.rstrip() for line in f if line != "\n"]
NUM_LISTS = 5
groups = [[] for i in range(NUM_LISTS)]
listIndex = 0
for line in lines:
if "Transactions/Sec for Group" not in line:
groups[listIndex].append(float(line))
listIndex += 1
if listIndex == NUM_LISTS:
listIndex = 0
value0 = groups[0]
value1 = groups[1]
value2 = groups[2]
value3 = groups[3]
value4 = groups[4]
for i in range(0, 5):
a = value0[i]
b = value1[i]
c = value2[i]
d = value3[i]
e = value4[i]
i += 1
report(a, b, c, d, e, index)
The Json file looks like:
[
{
"item": 1,
"command": "AA"
},
{
"item": 2,
"command": "BB",
},
{
"item": 3,
"command": "CC",
},
{
"item": 4,
"command": "DD",
},
{
"item": 5,
"command": "EE",
}
]
The text file looks like this:
Transactions/Sec for Group = AA\CODE1\KK
1011.5032
2444.8864
2646.6893
2740.8531
2683.8178
Transactions/Sec for Group = BB\CODE1\KK
993.2360
2652.8784
3020.2740
2956.5260
3015.5910
Transactions/Sec for Group = CC\CODE1\KK
1179.5766
3271.5700
4588.2059
4174.6358
4452.6785
Transactions/Sec for Group = DD\CODE1\KK
1112.2567
3147.1466
4014.8404
3913.3806
3939.0626
Transactions/Sec for Group = EE\CODE1\KK
1205.8499
3364.8987
4401.1702
4747.4354
4765.7614
The logic in the body of the program works fine. The groups appears ok, but instead of having the list from 1 to 5 from the Json file, is appearing everything with the number 5 command EE. Instead should appear: Item 1, 2, 3, 4, 5, with their commands
My list 1 will have the numbers: 1011.5032, 993.2360, 1179.5766, 1112.2567, 1205.8499.
My list 2 will have the numbers: 2444.8864, 2652.8784, 3271.5700, 3147.1466,
The python version I'm using is 2.6
Based on your explanation it's hard to tell what you're trying to do -- do you mean the nested loop below? The inner loop executes 5 times, but in every iteration it overwrites the previous values for item and cmd.
for node in data:
for i in range(0, 5):
item = data[i]['item']
cmd = data[i]['command']
index+= 1
Try printing the values each time the inner loop executes:
for node in data:
for i in range(0, 5):
item = data[i]['item']
cmd = data[i]['command']
print item, cmd
index+= 1
I think this code is your problem:
for node in data:
for i in range(0, 5):
item = data[i]['item']
cmd = data[i]['command']
Item will always be "5" and command will always be "EE" after this executes. Perhaps your indents are off for the code beneath it, and that code is supposed to be within the loop?

Categories