AttributeError: 'str' object has no attribute 'json' - python

I wrote little script on python 3.7 to receive actual browser version
Here is it:
import json
def json_open():
file_json = open('/Users/user/PycharmProjects/Test/configuration.json')
return json.load(file_json)
def get_last_version(browser_name):
f = json_open()
res = (f['global']['link_to_latest_browser_version'])
last_version = repr(res.json()['latest']['client'][browser_name]['version'])
#print(last_version[1:-1])
return last_version[1:-1]
Also, json file exists, but it does not matter now.
Received:
AttributeError: 'str' object has no attribute 'json'.
In row
last_version = repr(res.json()['latest']['client'][browser_name]['version'])
Please, tell me what is my mistake?

If you are trying to convert res as a json object try json.loads(res) instead of res.json()

Try this:
import json
FILEJSON = '/Users/user/PycharmProjects/Test/configuration.json'
def get_last_version(browser_name):
with open(FILEJSON, 'r') as fson:
res = json.load(fson)
last_version = res['global']['link_to_latest_browser_version']\
['latest']['client'][browser_name]['version'][1:-1]
return last_version
I think that the json_open function is unnecessary. Also take into account that the behavior of the json.load() method depends on the type of file you are reading.

Ok, the problem is here:
last_version = repr(res.json()['latest']['client'][browser_name]['version'])
A JSON object is basically a dictionary. So when you do json['key'] it returns the content, not a json object.
Here res is a string, not a json object and thus does not have the .json() attribute.
Edit:
If you want a string to be return in your situation:
res = json.loads(f['global']['link_to_latest_browser_version'])
last_version = res['latest']['client'][browser_name]['version']
return last_version

Your "res" variable is of type string.
Strings do not have an attribute called json.
So res.json() is invalid.

Related

Django Rest framework - I am trying to convert a property received in Response object to JSON object and iterate through it. But response is string

In views.py VENDOR_MAPPER is list of dictionary each dictionary has id, name, placeholder and autocommit key. I also tried sending json instead of Response object.
resp_object = {}
resp_object['supported_vendors'] = VENDOR_MAPPER
resp_object['vendor_name'] = ""
resp_object['create_vo_entry'] = False
resp_object['generate_signature_flag'] = False
resp_object['branch_flag'] = False
resp_object['trunk_flag'] = False
resp_object['branch_name'] = ""
resp_object['advisory'] = ""
data = {'data': resp_object}
return Response(data)
On home.html I am accessing the vendors_supported which is list and iterate through it, however instead of object i am getting string as type of variable.
var supported_vendors = "{{data.supported_vendors|safe}}";
console.log(supported_vendors);
console.log("Supported_vendors ", supported_vendors);
console.log("Supported_vendors_type:", typeof(supported_vendors));
data.supported_vendors|safe (django template tagging) is used to remove the unwanted characters in the response i have also tried without safe, but still the type was string
also tried converted as well as parse the response but type is shown as string
var supported_vendors = "{{data.supported_vendors}}";
console.log(JSON.parse(supported_vendors));
console.log(JSON.stringify(supported_vendors));
Output generated, i have printed the response type and values i get, also converting using JSON.parse and JSON.stringify did not work and output every time was string
[1]: https://i.stack.imgur.com/DuSMb.png
I want to convert the property into javascript object and perform some computations
You can try this instead ,
return HttpResponse(json.dumps(data),
content_type="application/json")
I got the answer:
var supported_vendors = "{{data.supported_vendors}}";
Converted the above line to
var supported_vendors = {{data.supported_vendors}};
removed quotes from the variable

Revit Python have problem with isinstance()

I use if isinstance(ins,list): to check . but it returned false Although ins is the List[Object]
def getname(ins):
name=[]
if isinstance(ins,list):
for i in ins:
name.append(i.Name)
else:
name.append(ins.Name)
return name
Levels = FilteredElementCollector(doc).OfClass(Level).ToElements()
ULevels = UnwrapElement(Levels)
Levelsname = getname(ULevels)
Error message is:
AttributeError: 'List[object]' object has no attribute 'Name'
You can do it in a single line of code like this:
[UnwrapElement(x).Name for x in FilteredElementCollector(doc).OfClass(Level).ToElements()]
Since I can see you are using Dynamo you can also do it like this:

getting an attribute from dictionary object django

I have a dictionary object namely person.json:
def get_web_parent(self, pk, is_ajax=False):
try:
person = models.Person.objects.active.get(pk=pk)
description = person.json
person.json is returning a dictionary like {dict}{'description':'example'}
How do I access description value.
I tried person.json.description but no luck.
you can use person.json.get("description", <<other value if key is missing>>)
assuming you get a Dict object.
If person.json is a JSON string you might need to use
person_dict = json.loads(person.json)
and then access it as
person_dict.get("description", "")

How to extract value with simplejson?

I have the following json string:
{"response":[[{"uid":123456,"name":"LA_"}],[{"cid":"1","name":"Something"}],[{"cid":1,"name":"Something-else"}]]}
How can I get Something value?
I do the following
jstr = json.loads(my_string)
if jstr.get('response'):
jstr_response = jstr.get('response')[1].get('name')
but it doesn't work ('list' object has no attribute 'get')
Try this.
jstr = json.loads(my_string)
if jstr.get('response'):
jstr_response = jstr.get('response')[1][0].get('name')

Django JSON serializable error

With the following code below, There is an error saying
File "/home/user/web_pro/info/views.py", line 184, in headerview,
raise TypeError("%r is not JSON serializable" % (o,))
TypeError: <lastname: jerry> is not JSON serializable
In the models code
header(models.Model):
firstname = models.ForeignKey(Firstname)
lastname = models.ForeignKey(Lastname)
In the views code
headerview(request):
header = header.objects.filter(created_by=my_id).order_by(order_by)[offset:limit]
l_array = []
l_array_obj = []
for obj in header:
l_array_obj = [obj.title, obj.lastname ,obj.firstname ]
l_array.append(l_array_obj)
dictionary_l.update({'Data': l_array}) ;
return HttpResponse(simplejson.dumps(dictionary_l), mimetype='application/javascript')
what is this error and how to resolve this?
thanks..
The quick read is that obj.lastname is a Lastname model not a String. You probably need to say something like:
l_array_obj = [..., obj.lastname.value, .... ]
to get the string value, rather than the Model object.
Have you considered using Django's own serialization functionality?

Categories