I have code that reads a list of numbers that are parameters for a python order:
def search(number):
url = "http://localhost:8080/sistem/checkNumberStatus"
payload = '{\n\"SessionName\":\"POC\",\n\"celFull\":\"'+number+'\"\n}'
headers = {
'Content-Type': 'application/json'
}
response = requests.request("POST", url, headers=headers, data = payload)
object = open('numbers_wpp.txt', 'r')
for numbers in object:
search(number)
But, when I print the payload of my json the output is:
{
"SessionName":"POC",
"celFull":"5512997708936
"
}
{
"SessionName":"POC",
"celFull":"5512997709337
"
}
{
"SessionName":"POC",
"celFull":"5512992161195"
}
When reading the file with 3 numbers, the quotes in the celFull attribute closed correctly only in the last loop (last number), while the first two were broken into quotes. This break is giving error in queries.
If numbers_wpp.txt is a file that has each number on a different line, the following code would iterate over the file line by line.
for number in object:
search(number) # <--- numbers is actually a line in your file.
Since each number is on a new line, the preceding line has a '\n' at the end.
So
123
456
Is actually
123\n456
So number is actually 123\n. This causes your payload to have a \n before the quote closes.
You could fix this by calling number.strip() which strips whitespace from either end of the string.
Alternatively, you should consider not using a handcrafted json string and let the requests library do that for you. Documentation
def search(number):
url = "http://localhost:8080/sistem/checkNumberStatus"
payload = {"SessionName": "POC", "celFull": number} # <-- python dict
response = requests.post(url, data=payload)
object = open('numbers_wpp.txt', 'r')
for line in object:
number = int(line.strip()) # <-- convert to an integer
search(number)
Related
json file =
{
"success": true,
"terms": "https://curr
"privacy": "https://cu
"timestamp": 162764598
"source": "USD",
"quotes": {
"USDIMP": 0.722761,
"USDINR": 74.398905,
"USDIQD": 1458.90221
}
}
The json file is above. i deleted lot of values from the json as it took too many spaces. My python code is in below.
import urllib.request, urllib.parse, urllib.error
import json
response = "http://api.currencylayer.com/live?access_key="
api_key = "42141e*********************"
parms = dict()
parms['key'] = api_key
url = response + urllib.parse.urlencode(parms)
mh = urllib.request.urlopen(url)
source = mh.read().decode()
data = json.loads(source)
pydata = json.dumps(data, indent=2)
print("which curreny do you want to convert USD to?")
xm = input('>')
print(f"Hoe many USD do you want to convert{xm}to")
value = input('>')
fetch = pydata["quotes"][0]["USD{xm}"]
answer = fetch*value
print(fetch)
--------------------------------
Here is the
output
"fetch = pydata["quotes"][0]["USD{xm}"]
TypeError: string indices must be integers"
First of all the JSON data you posted here is not valid. There are missing quotes and commas. For example here "terms": "https://curr. It has to be "terms": "https://curr",. The same at "privacy" and the "timestamp" is missing a comma. After i fixed the JSON data I found a solution. You have to use data not pydata. This mean you have to change fetch = pydata["quotes"][0]["USD{xm}"] to fetch = data["quotes"][0]["USD{xm}"]. But this would result in the next error, which would be a KeyError, because in the JSON data you provided us there is no array after the "qoutes" key. So you have to get rid of this [0] or the json data has to like this:
"quotes":[{
"USDIMP": 0.722761,
"USDINR": 74.398905,
"USDIQD": 1458.90221
}]
At the end you only have to change data["quotes"]["USD{xm}"] to data["quotes"]["USD"+xm] because python tries to find a key called USD{xm} and not for example USDIMP, when you type "IMP" in the input.I hope this fixed your problem.
I know this Question is already answered, but I dont know where the Error is in my Case.
This is my Code:
import json
json_data = """
{
'position1': '516, 440',
'position2': '971, 443',
'position3': '1186, 439',
'position4': '1402, 441',
'position5': '1630, 449',
'position6': '299, 681',
'position7': '518, 684',
'position8': '736, 691',
'position9': '739, 431'
}
"""
data = json.loads(json_data)
print(data)
Im not really into working with json files, so please don't blame me if it's a really dump mistake.
Don't use triple quotes """. Instead use a dictionary with json.dumps() so that commas in your values are not misinterpreted as commas between items.
import json
json_data = {
'position1': '516, 440',
'position2': '971, 443',
'position3': '1186, 439',
'position4': '1402, 441',
'position5': '1630, 449',
'position6': '299, 681',
'position7': '518, 684',
'position8': '736, 691',
'position9': '739, 431'
}
data = json.dumps(json_data)
print(data)
If you are using triple quotes, this would work
json_data = json_data.replace("'", '"')
data = json.loads(json_data)
print(data)
Try this one
import json
json_data = {
'position1': '516, 440',
'position2': '971, 443',
'position3': '1186, 439',
'position4': '1402, 441',
'position5': '1630, 449',
'position6': '299, 681',
'position7': '518, 684',
'position8': '736, 691',
'position9': '739, 431'
}
data = json.dumps(json_data)
print(data)
I'm using microsoft azure translator api to detect and translate the language the user is inputting and translating it back to english. After translating it, I'm printing the results in json format, which can be seen here: https://i.stack.imgur.com/Zcq9l.png
Afterwards, I'm trying to print whatever is translated after the 'text:' bit, however, I keep getting an error each time I try to do so. I tried using a for loop and referencing them, but it doesn't work.
Here is the code bit:
path = '/translate'
constructed_url = endpoint + path
params = {
'api-version': '3.0',
'to': ['en']
}
constructed_url = endpoint + path
headers = {
'Ocp-Apim-Subscription-Key': subscription_key,
'Ocp-Apim-Subscription-Region': location,
'Content-type': 'application/json',
'X-ClientTraceId': str(uuid.uuid4())
}
user_input = input("You: ")
body = [{
"text": user_input
}]
request = requests.post(constructed_url, params=params, headers=headers, json=body)
response = request.json()
json_data = json.dumps(response, sort_keys=True, ensure_ascii=False, indent=4, separators=(",", ": "))
print(json_data)
print("Translated Text: " + response.detectedLanguage.translations.text)
The final line is what's causing the error, but I'm not sure how to resolve it. I would appreciate if someone can guide me accordingly.
[1]: https://i.stack.imgur.com/Zcq9l.png
The object is a List of Dictionaries (just one in this case). As seen in the linked image.
In this particular case, to reach the translation text, you need to do:
response[0]["translations"]["text"]
I'm trying to import id from a JSON file but square brackets at the start/end of the JSON file for the 2nd JSON cause it to break. Here is the code I currently have to get id from json files:
import requests
url = 'http://benbotfn.tk:8080/api/cosmetics/search'
params = dict(
displayName='renegade raider',
)
resp = requests.get(url=url, params=params)
data = resp.json() # Check the JSON Response Content documentation below
json_id = data['id']
print(json_id)
This code works for any JSONs that don't start/end square brackets.
But when I change the JSON url to: http://benbotfn.tk:8080/api/cosmetics/search/multiple and run the same code, I get this error:
Traceback (most recent call last):
File "apigrabber.py", line 12, in <module>
json_id = data['id']
TypeError: list indices must be integers or slices, not str
To try and fix this, I tried to convert data to a string so that I can remove the square bracket by using this code:
import requests
url = 'http://benbotfn.tk:8080/api/cosmetics/search/multiple'
params = dict(
displayName='renegade raider',
)
resp = requests.get(url=url, params=params)
data = resp.json() # Check the JSON Response Content documentation below
nosquares = str(data).replace('[','').replace(']','')
json_id = nosquares['id']
print(nosquares)
But I then get the error:
Traceback (most recent call last):
File "apigrabber.py", line 13, in <module>
json_id = nosquares['id']
TypeError: string indices must be integers
Is there anyway I can fix the initial error (list indices must be integers or slices, not str) without converting it to a string?
print(data) as requested (raw):
[{"displayName":"Renegade Raider","backendType":"AthenaCharacter","icon":"http://benbotfn.tk:7071/static/AthenaCharacter/cid_028_athena_commando_f.png","description":"Rare renegade raider outfit.","backendRarity":"EFortRarity::Rare","gameplay_tags":["Cosmetics.Source.Season1.SeasonShop","Cosmetics.Set.StormScavenger","Cosmetics.UserFacingFlags.HasVariants"],"variants":{"STYLE":[{"name":"DEFAULT","icon":"http://benbotfn.tk:7071/static/CosmeticVariants/Game/UI/Foundation/Textures/Icons/Heroes/Athena/Soldier/T-Soldier-HID-028-Athena-Commando-F.T-Soldier-HID-028-Athena-Commando-F.png"},{"name":"CHECKERED","icon":"http://benbotfn.tk:7071/static/CosmeticVariants/Game/UI/Foundation/Textures/Icons/Heroes/Variants/T-Variant-F-RenegadeRaider-Variant.T-Variant-F-RenegadeRaider-Variant.png"}]},"id":"CID_028_Athena_Commando_F","type":"Outfit","rarity":"Rare"}]
print(data) - as requested (formatted):
[
{
"displayName":"Renegade Raider",
"backendType":"AthenaCharacter",
"icon":"http://benbotfn.tk:7071/static/AthenaCharacter/cid_028_athena_commando_f.png",
"description":"Rare renegade raider outfit.",
"backendRarity":"EFortRarity::Rare",
"gameplay_tags":[
"Cosmetics.Source.Season1.SeasonShop",
"Cosmetics.Set.StormScavenger",
"Cosmetics.UserFacingFlags.HasVariants"
],
"variants":{
"STYLE":[
{
"name":"DEFAULT",
"icon":"http://benbotfn.tk:7071/static/CosmeticVariants/Game/UI/Foundation/Textures/Icons/Heroes/Athena/Soldier/T-Soldier-HID-028-Athena-Commando-F.T-Soldier-HID-028-Athena-Commando-F.png"
},
{
"name":"CHECKERED",
"icon":"http://benbotfn.tk:7071/static/CosmeticVariants/Game/UI/Foundation/Textures/Icons/Heroes/Variants/T-Variant-F-RenegadeRaider-Variant.T-Variant-F-RenegadeRaider-Variant.png"
}
]
},
"id":"CID_028_Athena_Commando_F",
"type":"Outfit",
"rarity":"Rare"
}
]
When you are receiving list, you will have to fetch the id by parsing the list(which depends on what list you are getting), so the code flow should be like this:
....
data = resp.json()
if isinstance(data, dict):
id = data['id']
else:
# In this case you are getting list of dictionaries so you
# may get multiple id's.
# Response shared by you has only one dictionary in list.
for d in data: # Iterate over all dict in list
print(d['id'])
....
You can collect all id's in some list/set and use later in program, depending on your requrement.
Using requests library to execute http GET that return JSON response i'm getting this error when response string contains unicode char:
json.decoder.JSONDecodeError: Invalid control character at: line 1 column 20 (char 19)
Execute same http request with Postman the json output is:
{ "value": "VILLE D\u0019ANAUNIA" }
My python code is:
data = requests.get(uri, headers=HEADERS).text
json_data = json.loads(data)
Can I remove or replace all Unicode chars before executing conversion with json.loads(...)?
It is likely to be caused by a RIGHT SINGLE QUOTATION MARK U+2019 (’). For reasons I cannot guess, the high order byte has been dropped leaving you with a control character which should be escaped in a correct JSON string.
So the correct way would be to control what exactly the API returns. If id does return a '\u0019' control character, you should contact the API owner because the problem should be there.
As a workaround, you can try to limit the problem for your processing by filtering out non ascii or control characters:
data = requests.get(uri, headers=HEADERS).text
data = ''.join((i for i in data if 0x20 <= ord(i) < 127)) # filter out unwanted chars
json_data = json.loads(data)
You should get {'value': 'VILLE DANAUNIA'}
Alternatively, you can replace all unwanted characters with spaces:
data = requests.get(uri, headers=HEADERS).text
data = ''.join((i if 0x20 <= ord(i) < 127 else ' ' for i in data))
json_data = json.loads(data)
You would get {'value': 'VILLE D ANAUNIA'}
The code below works on python 2.7:
import json
d = json.loads('{ "value": "VILLE D\u0019ANAUNIA" }')
print(d)
The code below works on python 3.7:
import json
d = json.loads('{ "value": "VILLE D\u0019ANAUNIA" }', strict=False)
print(d)
Output:
{u'value': u'VILLE D\x19ANAUNIA'}
Another point is that requests get return the data as json:
r = requests.get('https://api.github.com/events')
r.json()