Skip to content
Advertisement

Convert nested list to JSON using Python

I’m using the following SQL query to get data for every month in a given year:

SELECT DATE_FORMAT(tour_date , '%M'), COUNT(*)
FROM _673338137185
WHERE tour_date LIKE '{tour_year}%'
GROUP BY DATE_FORMAT(tour_date , '%M')

When I’m returning this via Python, I’m getting the following result:

[
    [
        [
            "April",
            9
        ],
        [
            "August",
            5
        ],
        [
            "February",
            3
        ],
        [
            "July",
            6
        ],
        [
            "June",
            3
        ],
        [
            "March",
            1
        ],
        [
            "May",
            8
        ],
        [
            "November",
            1
        ],
        [
            "October",
            2
        ],
        [
            "September",
            4
        ]
    ]
]

Also, there are n everywhere in the result. I need the result in JSON format, but I can’t get it right. How can I do it?

Advertisement

Answer

If l is the list you display, simple use json.dumps:

import json

print(json.dumps(l))

# Output
[[["April", 9], ["August", 5], ["February", 3], ["July", 6], ["June", 3], ["March", 1], ["May", 8], ["November", 1], ["October", 2], ["September", 4]]]
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement