OnbasiSoner OnbasiSoner - 2 years ago 149
JSON Question

How can i create the json object on python?

I tried to create a json object but I made a mistake somewhere. I'm getting some data on CSV file (center is string, lat and lng are float).

My codes:

data = []
'id': 'id',
'is_city': false,
'name': center,
'county': center,
'cluster': i,
'cluster2': i,
'avaible': true,
'is_deleted': false,
'coordinates': ('{%s,%s}' %(lat,lng))
json_data = json.dumps(data)
print json_data

It goes with this:

"county": "County",
"is_city": false,
"is_deleted": false,
"name": "name",
"cluster": 99,
"cluster2": 99,
"id": "id",
"coordinates": "{41.0063945,28.9048234}",
"avaible": true

That's I want:

"id" : "id",
"is_city" : false,
"name" : "name",
"county" : "county",
"cluster" : 99,
"cluster2" : 99,
"coordinates" : [
"available" : true,
"isDeleted" : false,

Answer Source

You are defining coordinates to be a string of the specified format. There is no way json can encode that as a list; you are saying one thing when you want another.

Similarly, if you don't want the top-level dictionary to be the only element in a list, don't define it to be an element in a list.

data = {
    'id': 'id',
    'is_city': false,
    'name': name,
    'county': county,
    'cluster': i,
    'cluster2': i,
    'available': true,
    'is_deleted': false,
    'coordinates': [lat, lng]

I don't know how you defined center, or how you expected it to have the value 'name' and the value 'county' at basically the same time. I have declared two new variables to hold these values; you will need to adapt your code to take care of this detail. I also fixed the typo in "available" where apparently you expected Python to somehow take care of this.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download