简体   繁体   中英

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 = []
data.append({
    '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" : [
        41.0870185, 
        29.0235126
    ], 
    "available" : true, 
    "isDeleted" : false, 
}

You can use pprint to make pretty printing at python, but it should be applied on object not string. At your case json_data is a string that represents a JSON object, so you need to load it back to be an object when you try to pprint it, (or to use the data variable itself since it already contains this JSON object in your example)

for example try to run: pprint.pprint(json.loads(json_data))

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM