Вопрос

I understand how to send a simple JSON in python.

What I can't find is how to make a more complex JSON object. It doesn't even need to be very complex, I am simply testing out Google Cloud Messaging, and I need to send something that looks like this:

{
    "collapse_key" : "Food-Promo",
    "time_to_live" : 3600,
    "delay_while_idle" : "true",
    "data" : {
        "Category" : "FOOD",
        "Type": "VEG",
    }
    "registration_ids": ["APA4lj5jl54l2h..."],
},

I have not been able to find a way to do this in Python. Most of my experience is with Java, so maybe that's part of why I can't find this, because it seems it would be simple and I'm worried I've already seen a solution and passed over it. Any help would be greatly appreciated.

Это было полезно?

Решение

>>> myDict = {'x' : 1, 'y' : 2}
>>> myList = [1,2,3]
>>> post = {'uname' : 'jon', 'node' : myDict, 'access-levels' : myList}
>>> json.dumps(post)
'{"node": {"y": 2, "x": 1}, "uname": "jon", "access-levels": [1, 2, 3]}'
>>> 

Другие советы

data is just a nested dictionary. That is, it's just the same as any other element of the dictionary, except that its value is itself a dictionary.

If you were building up the object line by line (which you would almost certainly never do) you might do something like this:

obj = {}

obj["collapse_key"] = "Food-Promo"
obj["time_to_live"] = 3600,
obj["delay_while_idle" : "true",

data = {}
data["Category"] = "FOOD"
data["Type"] = "VEG"

obj["data"] = data

obj["registration_ids"] = ["APA4lj5jl54l2h..."]
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top