MarkO
MarkO

Reputation: 795

How to parse JSON in a Django View

I post some JSON to a view. I want to now parse the data and add it to my database.

I need to get the properties name and theme and iterate over the array pages. My JSON is as follows:

{
    "name": "xaAX",
    "logo": "",
    "theme": "b",
    "fullSiteLink": "http://www.hello.com",
    "pages": [
        {
            "id": "1364484811734",
            "name": "Page Name",
            "type": "basic",
            "components": {
                "img": "",
                "text": ""
            }
        },

        {
            "name": "Twitter",
            "type": "twitter",
            "components": {
                "twitter": {
                    "twitter-username": "zzzz"
                }
            }
        }
    ]
}

Here is what I have so far:

def smartpage_create_ajax(request):

    if request.POST:

         # get stuff and loop over each page?

       return HttpResponse('done')

Upvotes: 2

Views: 3207

Answers (1)

dm03514
dm03514

Reputation: 55972

python provides json to encode/decode json

import json
json_dict = json.loads(request.POST['your_json_data'])
json_dict['pages']

[
    {
        "id": "1364484811734",
        "name": "Page Name",
        "type": "basic",
        "components": {
            "img": "",
            "text": ""
        }
    },

    {
        "name": "Twitter",
        "type": "twitter",
        "components": {
            "twitter": {
                "twitter-username": "zzzz"
            }
        }
    },

    }
]

Upvotes: 5

Related Questions