Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: Object of type 'Tag' is not JSON serializable

I am trying to create a JSON object and send it to the Firebase Database using python, but when I do this I get:

TypeError: Object of type 'Tag' is not JSON serializable

Here is my code:

data = {'address': address,
    'name': name
   }

print(type(data))
sent = json.dumps(data)
result = firebase.post("/tHouse/houseTest", sent)  

The is something wrong with json.dumps(data) since the error is pointed out here. Running print(type(data)) returns though <class 'dict'>.

Also the name and address are set beforehand

like image 528
anho Avatar asked Jul 13 '17 08:07

anho


People also ask

Is not JSON serializable meaning?

The Python "TypeError: Object of type function is not JSON serializable" occurs when we try to serialize a function to JSON. To solve the error, make sure to call the function and serialize the object that the function returns.

What is a JSON serializable object?

It is a format that encodes the data in string format. JSON is language independent and because of that, it is used for storing or transferring data in files. The conversion of data from JSON object string is known as Serialization and its opposite string JSON object is known as Deserialization.

Why is Python set not JSON serializable?

Conclusion # The Python "TypeError: Object of type set is not JSON serializable" occurs when we try to convert a set object to a JSON string. To solve the error, convert the set to a list before serializing it to JSON, e.g. json. dumps(list(my_set)) .

How do you make a class JSON serializable in Python?

Use toJSON() Method to make class JSON serializable So we don't need to write custom JSONEncoder. This new toJSON() serializer method will return the JSON representation of the Object. i.e., It will convert custom Python Object to JSON string.


1 Answers

Being a bs4.element.Tag, address can not be serialised to JSON.

How you handle this depends on what part of the tag you want to store in your db. If you just call str() on the Tag the output will include the XML/HTML markup. If you want the text contained within the tag, access the .text attribute e.g.

from bs4 import BeautifulSoup

soup = BeautifulSoup('<address>1 Some Street Somewhere ABC 12345</address>')
address = soup.address

>>> type(address)
<class 'bs4.element.Tag'>
>>> str(address)
'<address>1 Some Street Somewhere ABC 12345</address>'
>>> address.text
u'1 Some Street Somewhere ABC 12345'

So this might be what you need to do:

data = {'address': address.text, 'name': 'Some One'}
>>> json.dumps(data)
'{"name": "Some One", "address": "1 Some Street Somewhere ABC 12345"}'
like image 65
mhawke Avatar answered Sep 20 '22 04:09

mhawke