I want to create a data structure that will be parse as a JSON object. The out put must look like this and this should be a dynamic data structure.
{"data": [{"type": "locale", "lat": -34.43778387240597, "lon": 150.04799169921876},
{"type": "poi", "lat": -34.96615974838191, "lon": 149.89967626953126},
{"type": "locale", "lat": -34.72271328279892, "lon": 150.46547216796876},
{"type": "poi", "lat": -34.67303411621243, "lon": 149.96559423828126}]}
I'm struggling in the middle of implementing this data structure so expecting some good ideas.
Thanks
As response to the comment on Mathiasdm answer: You mean how to create dictionary with a list of dictionaries? That can be done like this:
dict = {}
dict["data"] = []
dict["data"].append({'type': 'poi', 'lat': 123})
dict["data"].append({'type': 'locale', 'lat': 321})
And so on.
But if this was really the problem, i would suggest to read the reference for lists and dictionaries again: http://docs.python.org/tutorial/datastructures.html
Your question is unclear, but do you want probably something like this:
>>> r = DataResult()
>>> r.add_poi(-34.96615974838191, 149.89967626953126)
>>> r.add_locale(-34.72271328279892, 150.46547216796876)
>>>r.add_poi(-34.67303411621243, 149.96559423828126)
>>> print r
{"data": [{"type": "locale", "lat": -34.43778387240597, "lon": 150.04799169921876},
{"type": "poi", "lat": -34.96615974838191, "lon": 149.89967626953126},
{"type": "locale", "lat": -34.72271328279892, "lon": 150.46547216796876},
{"type": "poi", "lat": -34.67303411621243, "lon": 149.96559423828126}]}
You can create this by creating a DataResult
class and overriding the __str__
or __unicode__
methods.
Your add_poi
can be something like:
def add_poi(self, lat, lon):
self.append(PoiData(lat, lon))
where PoiData
is another class representing a data entry of type "poi" etc.
What exactly do you mean? If you create a data structure composed of dicts and lists (like the one you have given), you can always parse it to a JSON object using the json package .
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.