Hi I'm trying to pass json in terminal as a payload input but after passing argument in terminal I got json without double quotes, I want to have my response output in json format as well.
How do I stop removing double quotes after passing command-line argument?
Here is my code,
def get_apicall():
Token = get_token()
url = "http://localhost.../resp"
Header = {'Content-Type': "application/json", 'Authorization': 'Bearer ' + str(Token)}
payload = sys.argv[1]
print(payload)
payload1 = json.dumps(payload )
print(payload1)
response = requests.request("POST", url, data=payload1, headers=Header)
print(response.text)
get_endpoint()
My input json is { "request":"success","input":[ { "type":" ", "content":[ { "type":" ", "meta":{ "sample_type":" " , deatail":" "} ] } ], "output":[ { "type":" ","content":[ { "type":"", "meta":{ "sample_type":"", }, "deatils":" " } ] } ] }
When I'm trying to print input payload which I passed in teminal payload = sys.argv[1] print(payload)
but I got this when I did print(payload) which removed double qoutes : { request:success,input:[ { type: , content:[ { type: , meta:{ sample_type: , deatail: } ] } ], output:[ { type: ,content:[ { type:, meta:{ sample_type:, }, deatils: } ] } ] }
please correct me if I'm wrong some where in my above code.
I want to have print(payload) same as my input payload
{ "request":"success","input":[ { "type":" ", "content":[ { "type":" ", "meta":{ "sample_type":" " , deatail":" "} ] } ], "output":[ { "type":" ","content":[ { "type":"", "meta":{ "sample_type":"", }, "deatils":" " } ] } ] }`
Using the print() function can apply different formatting for printing. Maybe try using repr() function which will show the object based on the way Python is interpreting it. I.e. it will include type information like quotes for strings, square brackets for lists, and curly braces for dictionaries.
You're trying to print JSON using print(), which formats JSON (removes double quotes).
If you want to keep the quotes in the output, use json.dumps() (docs) in print() instead. That is, just replace print(payload) with print(json.dumps(payload)) in your code.
So, the following code will work for you:
import json
print(json.dumps(payload))
Related
I have a Json data, where I want to get the value of "authorization" i.e "OToken
DEDC1071B77800A146B6E8D2530E0429E76520C151B40CC3325D8B
6D9242CBA3A6BFA643E7E5596FBEBAE0F46A1FB1BCD099EBC1F59D
CD82F390B6BC45FCE036F37F7F589BD687A691E1378F1FF432331C
62E7E641E857C8F8A405A4BFE2F01B1EB8F3C69817D45F5DDE9DEE
346ACABA1B7208DECA9E43CCE7AB3761553E23D9CB36A870C1819C
15C7C4B1CFE2802DFD05F651AA537AB81787.4145535F55415431" using python
{
"links":[
{
"method":"GET",
"rel":"self",
"href":"https://www.sampleurl.com/request"
},
{
"headers":{
"authorization":"OToken
DEDC1071B77800A146B6E8D2530E0429E76520C151B40CC3325D8B
6D9242CBA3A6BFA643E7E5596FBEBAE0F46A1FB1BCD099EBC1F59D
CD82F390B6BC45FCE036F37F7F589BD687A691E1378F1FF432331C
62E7E641E857C8F8A405A4BFE2F01B1EB8F3C69817D45F5DDE9DEE
346ACABA1B7208DECA9E43CCE7AB3761553E23D9CB36A870C1819C
15C7C4B1CFE2802DFD05F651AA537AB81787.4145535F55415431"
},
"valid_date":"2020-08-17T15:49:00+0530",
"method":"POST",
"rel":"redirect",
"href":"https://www.billdesk.com/pgi/MerchantPayment/",
"parameters":{
"mercid":"BDMERCID",
"bdorderid":"OAFC19XTFD8TSP"
}
}
]
}
import json
response = YOUR_JSON_STRING
data = json.loads(response)
authorization = data['headers']['authorization']
I am using Elasticsearch library in python to query an elasticsearch server like below:
query = {
"query":{
"match_all":{}
}
}
es = Elasticsearch('localhost:9200')
res = es.search(index='myindex', body=query)
with open('response.json', 'w') as out:
out.write(res)
# json.dump(res, out) also gives the same result
the output I save to file has the format
{
'key':'value',
'key2': {
'key3' : 'value2'
}
}
Notice the single quotes here. I know I can do a simple find and replace or use sed to change single quotes to double, however, I want to know why this is happening when with curl from terminal it is not the case.
I would prefer to have the output dumped in a proper json format
Python dictionary object is not necessarily automatically in json format. The above issue can be solved by using json.dumps() on the response like below:
query = {
"query":{
"match_all":{}
}
}
es = Elasticsearch('localhost:9200')
res = es.search(index='myindex', body=query)
with open('response.json', 'w') as out:
out.write(json.dumps(res))
This will turn res into json format like below:
{
"key":"value",
"key2": {
"key3" : "value2"
}
}
I have a json response that looks like below and I would like to count how many times corrId has been mentioned.
{
"result":
{
"corrList":[
{
"corrId":123456,
"title":"sample1",
},
{
"corrId":45678,
"title":"sample2",
},
{
"corrId":987654,
"title":"sample3",
}
],
"find":true
}
}
For the above, I would expect result to be 3
I have tried something like above, but it throws an error:
r = requests.get(url = HOSTNAME + endpoint, headers = headers, verify=False)
data = json.loads(r.text)
corrList = len(data['corrList'][0]['corrId'])
print (corrList)
My error:
TypeError: object of type 'int' has no len()
Would someone be able to help? thanks in advance!
You need to actually count the number of dicts that have that key:
data = {
"result":
{
"corrList":[
{
"corrId":123456,
"title":"sample1",
},
{
"corrId":45678,
"title":"sample2",
},
{
"corrId":987654,
"title":"sample3",
}
],
"find":True
}
}
corrList = [item for item in data['result']['corrList'] if 'corrId' in item]
print(len(corrList))
Output 3
What is wrong here?
query='{ repositoryOwner(login : "ALEXSSS") { login repositories (first : 30){ edges { node { name } } } } }'
headers = {'Authorization': 'token xxx'}
r2=requests.post('https://api.github.com/graphql', '{"query": \"'+query+'\"}',headers=headers)
print (r2.json())
I've got
{'message': 'Problems parsing JSON', 'documentation_url': 'https://developer.github.com/v3'}
but this snippet of code below works correctly
query1= '''{ viewer { login name } }'''
headers = {'Authorization': 'token xxx'}
r2=requests.post('https://api.github.com/graphql', '{"query": \"'+query1+'\"}',headers=headers)
print (r2.json())
I've tried out to change quotes (from " into ' or with " and so on) but it doesn't work.
The problem is related with the double quotes (").
On the first snippet, when you join the '{"query": \"'+query+'\"}' with the query variable, you get the following result:
{"query": "{ repositoryOwner(login : "ALEXSSS") { login repositories (first : 30){ edges { node { name } } } } }"}
Notice how the double quote from "ALEXSSS" are not escaped, therefore the resultant string is not a json valid format.
When you run the second snippet, the resultant string is:
{"query": "{ viewer { login name } }"}
which is a valid json string.
The easiest and best solution is simply use the JSON library instead of trying to do it manually, so you won't need to worry about escaping characters.
import json
query='{ repositoryOwner(login : "ALEXSSS") { login repositories (first : 30){ edges { node { name } } } } }'
headers = {'Authorization': 'token xxx'}
r2=requests.post('https://api.github.com/graphql', json.dumps({"query": query}), headers=headers)
print (r2.json())
But remember that you could also just escape the characters on the query manually:
query='{ repositoryOwner(login : \"ALEXSSS\") { login repositories (first : 30){ edges { node { name } } } } }'
headers = {'Authorization': 'token xxx'}
r2=requests.post('https://api.github.com/graphql', '{"query": "'+query1+'"}', headers=headers)
print (r2.json())
it works as expected :)
I am trying to automate some queries to a API using Python. The problem is that the request needs to be created in a special way, and I just cant make it work. This is the part of the string I am having problems creating.
payload = "{\n \"filter\": {\n \"name\":[\"name1\", \"name2\"]\n }"
Where name1 and name2 is variable and is created from a list. The way I tried to do it was just to first create a function to create the
[\"name1\", \"name2\"]
This is the function
def create_string(list_of_names):
#Creates the string of line items we want data from
start = '[\\"%s\\"' % list_of_names[0]
for i in list_of_names[1 : ]:
start += ', \\"%s\\"' %(i)
start += "]"
return start
list_of_names = ['name1', 'name2']
And then just using the %s part to add it into the string.
payload = "{\n \"filter\": {\n \"name\":%s\n }" % create_string(list_of_names)
This doesnt work, and I can think this has something to do with how the \ is used in Python.
The create_string function creates different output depening on if I am printing it or not.
a = create_string(list_of_names)
print(a)
Creates the string I need to pass in using %s
[\"name1\", \"name2\", \"name3\"]
And just a outputs
'[\\"name1\\", \\"name2\\", \\"name3\\"]'
So my problem is then how to pass the print(a) part into the payload string. Does anyone have some sort of solution to this?
Instead of creating your payload by hand, first create a python dictionary and use the json-module to convert it to a string:
payload = {"filter": {"name": list_of_names]}}
payload = json.dumps(payload)
or with your more complex dictionary:
payload = {
"filter": {
"date": "pastThirtyDays",
"lineitem": {
"buyType": "RTB",
"name": list_of_names,
}
},
"metrics": ["cost"],
"dimensions": ["date", "lineItem"],
}
payload = json.dumps(payload)