Skip to content

Instantly share code, notes, and snippets.

@gifguide2code
Last active December 30, 2022 16:45
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gifguide2code/4f337564129c7879da3ebc0089c2cf21 to your computer and use it in GitHub Desktop.
Save gifguide2code/4f337564129c7879da3ebc0089c2cf21 to your computer and use it in GitHub Desktop.
Converts a Google Location JSON file into a CSV with Timestamp, Latitude, and Longitude.
import re
import json
import csv
JSON_data="C:/Users/JSON FILE PATH.txt"
CSV_file="C:/Users/CSV FILE PATH.csv"
with open(JSON_data) as f:
data = json.load(f)
csv_f=open(CSV_file, 'w')
for x in range(len(data["locations"])):
regex_Time=re.findall(".timestampMs.: .\d\d\d\d\d\d\d\d\d\d\d\d\d.", str(data["locations"][x]))
regex_Lat=re.findall(".latitude...: -?\d\d\d\d\d\d\d\d\d", str(data["locations"][x]))
regex_Long=re.findall(".longitude...: -?\d\d\d\d\d\d\d\d\d", str(data["locations"][x]))
csv_f.write(regex_Time[0] + "," + regex_Lat[0] + "," + regex_Long[0]+'\n')
csv_f.close
print('Done')
@gifguide2code
Copy link
Author

Sorry for the late response troldmand and balwit! I was working with my data in mind when I wrote the script, and my JSON file only contains coordinates from North America. So my latitude (measured from the equator) is always positive, and my longitude (measured from the Prime Meridian in Great Britain) is always negative. That would explain why removing the dash was somewhat successful if you're hailing from somewhere on the other side of the Prime Meridian. It wouldn't work if you were trying anything south of the equator though, so I'm updating this a bit.

? in regex can be used to match 0 or 1 of whatever is immediately before it, so I'm thinking if we place a -? before the digit sequence, it'll catch a negative if it's there and nothing if it's not.

Hope that helps! Thanks for commenting--it would have never occurred to me that people from other parts of the globe would try it.

@rrodrigo11
Copy link

Hi! I just tried, but ran into this:

Traceback (most recent call last):
  File "script.py", line 16, in <module>
    csv_f.write(regex_Time[0][16:-1] + "," + regex_Lat[0][14:] + "," + regex_Long[0][15:]+'\n')
IndexError: list index out of range

Is it a 'known issue' or did I likely just do something wrong?

Hello!
Working with my data ran into the same issue + some adjustments that I needes to made because my Records.json

Renamed values:

  • latitude -> latitudeE7
  • longitude -> longitudeE7
  • timestampsMS -> timestamp & Unix time -> yyyy-MM-dd'T'HH:mm:ss.SSS'Z'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment