I have a list with json data as below:
txt
["{'type': 'Point', 'coordinates': [35.51635659, 139.5662442]}", "{'type': 'Point', 'coordinates': [51.50178423, -0.05362636]}"]
I'm trying to extract the long and lat from coordinates but i'm really struggling with this.
When I try:
for each in txt:
print(each)
it returns:
{'type': 'Point', 'coordinates': [35.51635659, 139.5662442]} {'type': 'Point', 'coordinates': [51.50178423, -0.05362636]}
when i try:
json_normalize(json.loads(txt))
I get the following error:
TypeError Traceback (most recent call last) in ----> 1 json_normalize(json.loads(txt))
C:\\ProgramData\\Anaconda3\\lib\\json__init__.py in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw) 339 else: 340 if not isinstance(s, (bytes, bytearray)): --> 341 raise TypeError(f'the JSON object must be str, bytes or bytearray, ' 342 f'not {s. class . name }') 343 s = s.decode(detect_encoding(s), 'surrogatepass')
TypeError: the JSON object must be str, bytes or bytearray, not list
If anyone could help it would be much appreciated
Thank you
The dictionary is a string, so you'd need to either use ast.literal_eval()
, or replace with double quotes then use json.loads()
. either way can get the coordianates:
Given:
txt = ["{'type': 'Point', 'coordinates': [35.51635659, 139.5662442]}", "{'type': 'Point', 'coordinates': [51.50178423, -0.05362636]}"]
Option 1:
import json
for each in txt:
each = each.replace("'", '"')
jsonObj = json.loads(each)
print (jsonObj['coordinates'])
Option 2:
import ast
for each in txt:
each = ast.literal_eval(each)
print(each['coordinates'])
Output:
[35.51635659, 139.5662442]
[51.50178423, -0.05362636]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.