1

There is a lot of information on loading .json files, but I just cannot figure out what the problem is:

I have an external file called LocationHistory.json with various coordinates inside. For reference sake, this is how the data is listed:

{
    "data" : {
      "items" : [ {
        "kind" : "latitude#location",
        "timestampMs" : "1374870896803",
        "latitude" : 34.9482949,
        "longitude" : -85.3245474,
        "accuracy" : 2149
      }, {
        "kind" : "latitude#location",
        "timestampMs" : "1374870711762",
        "latitude" : 34.9857898,
        "longitude" : -85.3526902,
        "accuracy" : 2016
      }, {
        "kind" : "latitude#location",
        "timestampMs" : "1374870651752",
        "latitude" : 34.9857898,
        "longitude" : -85.3526902,
        "accuracy" : 2016
      }]
   }
 }

I'm trying to parse this information with:

import json

json_file = open ('LocationHistory.json')
json_string = json_file.read() 
json_data = json.loads (json_string) 

locations = json_data ["data"]

for location in locations:
    print location["timestampMS"], location["latitude"], location["longitude"], location["accuracy"]

Why am I getting the error:

line 10, in

print location["timestampMS"], location["latitude"], location["longitude"], location["accuracy"]

TypeError: string indices must be integers

All the information I can find to parse .json files explains this type of solution that I have. Where am I going wrong?

Thanks in advance, I'm sure it should be a simple mistake...

1 Answer 1

1

You want to iterate over data items instead:

locations = json_data["data"]["items"]
for location in locations:  # now "locations" is a list of dictionaries
    # ...
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much @alecxe, this solved my problem. All the information I could get always showed single lists not like mine with "data" with "list" in it. I appreciate your help
alecxe, how do I parse the JSON data file into KML format rather than printing it out? Thanks :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.