I have a string causing a bit of a problem. This is my string.
my_string = "'{'place_id': X, 'licence': 'X', 'osm_type': 'X', 'osm_id': X,'boundingbox': X, 'lat': 'X', 'lon': 'X', 'display_name': 'X', 'class': 'X', 'type': 'X','importance': X})'"
If I don't have "'
at the beginning and '"
at the end, it's not treated as a string.
Maybe I am creating the string the wrong way. Not sure. Anyway, this is what I end up with.
["'{'place_id': X, 'licence': 'X', 'osm_type': 'X'}'",
{'place_id': 177948251,
'licence': 'Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright',
'osm_type': 'way'},
{'place_id': 306607940,
'licence': 'Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright',
'osm_type': 'way'}]
I'm trying to convert this list to a dataframe but I'm getting this error:
'AttributeError: 'str' object has no attribute 'keys''
I think the problem comes from the first item in the list having this:
"'
and '"
So, I tried to do a str.replace on the items in the list, like this.
new_strings = []
for j in final_list:
new_string = str.replace("""'{""", "{")
new_string = str.replace("""}'""", "}")
new_strings.append(new_string)
my_df = pd.DataFrame(new_string)
When I try to run that, I get this error.
Traceback (most recent call last):
File "<ipython-input-83-424d9a0504f8>", line 3, in <module>
new_string = str.replace("""'{""","{")
TypeError: replace expected at least 2 arguments, got 1
Any idea how to get this straightened out?
CodePudding user response:
Maybe this helps you. Note that I putted ' around X as I think it is a typo in the original one.
import json
old_list = [
"'{'place_id': 'X', 'licence': 'X', 'osm_type': 'X'}'",
{
'place_id': 177948251,
'licence': 'Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright',
'osm_type': 'way'
},
{
'place_id': 306607940,
'licence': 'Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright',
'osm_type': 'way'
}
]
new_list = []
for item in old_list:
if isinstance(item, str):
# if we strip the surrounding ' and replace all other ' with "
# this looks like a json document
item_json = item.strip("'").replace("'", '"')
item_dict = json.loads(item_json)
new_list.append(item_dict)
elif isinstance(item, dict):
# perfect, we can keep this item as it is
new_list.append(item)
else:
# oh oh, we got an unexpected type
raise TypeError