SteakOverCooked SteakOverCooked - 5 months ago 8
Python Question

How to parse this JSON data to list in Python?

I have a json file which looks like this:

[{"lat":51.877743,"lng":-0.4116338,"acc":0,"time":0},`{"lat":51.877743,"lng":-0.4116338,"acc":20,"time":1465386382293},{"lat":51.877743,"lng":-0.4116338,"acc":20,"time":1465386412347}, ...`


I read them using the following code:

import json

with open('data.json') as data_file:
data = json.load(data_file)


and the data looks like this:

data
Out[18]:
[{u'acc': 0, u'lat': 51.877743, u'lng': -0.4116338, u'time': 0},
{u'acc': 20, u'lat': 51.877743, u'lng': -0.4116338, u'time': 1465386382293L},
{u'acc': 20, u'lat': 51.877743, u'lng': -0.4116338, u'time': 1465386412347L},


I want to extract the 'lat' and 'lng' fields into a list like this:

array([[ 0.37291534, 0.90496579],
[ 0.43889613, 0.62523318],
[ 0.96554937, 0.73811836],
[ 0.9254325 , 0.51556322],
[ 0.26246525, 0.01470611],
[ 0.73168115, 0.99624888],
[ 0.38049958, 0.28766334],
[ 0.94917181, 0.60546656],
[ 0.52672308, 0.60608954],
[ 0.03778316, 0.92360363]])


How can I do it?

Answer

You can try something along these lines:

what_you_want = [[e['lat'], e['lng']] for e in data]

This can further be converted to array, or better yet, to a numpy.array.

I cannot help but to also suggest that you take a look at pandas.DataFrame.

Comments