3

I have written a Python script that outputs a long data structure (dictionary i called "celldict") in Json format. Here's a small part of it :

{
    "1224": {
        "OUT3FA_5": 12,
        "IN1": 37,
        "Total_IN1": 37
    },
    "1225": {
        "OUT3FA_5": 24,
        "IN1": 59,
        "Total_IN1": 22
    }
}

But what I would like to do is have something like this :

{
    "success": true,
    "data": [
        {
            "Week":"1224",
            "OUT3FA_5": 65,
            "IN1": 85,
            "Total_IN1": 100
        },
        {
            "Week":"1225",
            "OUT3FA_5": 30,
            "IN1": 40,
            "Total_IN1": 120
        }
    ]
}

Is there a way to format the json output with Python to get I what I want? I do:

print json.dumps(celldict)

to get my output. Any help would be much much appreciated.

salamey
  • 3,633
  • 10
  • 38
  • 71

2 Answers2

9

Just put celldict inside another dict:

json.dumps({'success': True, 'data': celldict.values()})

You'll have to add the Week key to the celldict dictionaries first:

for d in celldict.itervalues():
    celldict['Week'] = '1238'

or use create a copy of each dict on-the-fly:

json.dumps({'success': True, 'data': [dict(d, Week='1238') for d in celldict.values()]})

The latter method, with some indentation, produces:

>>> print json.dumps({'success': True, 'data': [dict(d, Week='1238') for d in celldict.values()]}, indent=4)
{
    "data": [
        {
            "OUT3FA_5": 24, 
            "Week": "1238", 
            "Total_IN1": 22, 
            "IN1": 59
        }, 
        {
            "OUT3FA_5": 12, 
            "Week": "1238", 
            "Total_IN1": 37, 
            "IN1": 37
        }
    ], 
    "success": true
}

Reading between the lines, it seems as if the 1224 and 1225 keys in your input example are actually the week numbers you are referring to. If so, they are easily incorporated:

json.dumps({'success': True, 'data': [dict(d, Week=k) for k, d in celldict.iteritems()]})

would produce:

{
    "data": [
        {
            "OUT3FA_5": 24, 
            "Week": "1225", 
            "Total_IN1": 22, 
            "IN1": 59
        }, 
        {
            "OUT3FA_5": 12, 
            "Week": "1224", 
            "Total_IN1": 37, 
            "IN1": 37
        }
    ], 
    "success": true
}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Thanks! And what about the "Week" string that I would like to add too? You see what I need is to put `"Week"` before every key (represented by the numeric values 1224 and 1225) of my dict. – salamey Nov 28 '12 at 14:59
  • @user1734229: You can add those yourself by updating the dictionaries in `celldict` easily enough, right? – Martijn Pieters Nov 28 '12 at 15:00
  • Yes this is great! But before I accept your answer, I see you've put 1238 in week while I want to get each week (suppose I have many weeks), how can I access dict's keys and assign them to `Week=` ? – salamey Nov 28 '12 at 16:03
  • @user1734229: What is the weeknumber *based* on? How do you determine it? I hardcoded the value because you didn't provide any information about how you determine that number. It's easy enough to set different numbers for each entry, if there is a rule to follow. – Martijn Pieters Nov 28 '12 at 16:03
  • Well this structure actually comes from an Excel file, I iterate through it using the `xlrd` library, my first column contains all the weeks and my second column contains the other data. What I do is I calculate for each week value, the number of times "IN1" "OUT3FA_5" occurs (it's just summing basically). And that's what gives me the first structure. I do this : `celldict[first_column_cell][second_column_cell] += 1` – salamey Nov 28 '12 at 16:10
  • @user1734229: then include the weeknumber in your `celldict` structure in the first place. We cannot guess where that data comes from by ourselves. :-) At a glance, I guess `celldict[first_column_cell]['Week'] = weeknumber` would be what you are looking for. – Martijn Pieters Nov 28 '12 at 16:13
  • @user1734229: Wait a sec, did you perhaps mean that the `first_column_cell` values are the week numbers? Thus the `1224` and `1225` numbers in your input example here? Then *make that clear* in your question. Your output uses *totally* different numbers, so there is no correlation for us to guess at there. – Martijn Pieters Nov 28 '12 at 16:16
  • I am really sorry I didn't notice my mistake, I corrected my output. Thank you so much for helping me all the way. – salamey Nov 28 '12 at 16:26
0

The json module follows the structure of your data, so to get your desired output you'll have to rearrange the data. You could construct a new dictionary like this:

data = []
for week, values in celldict.iteritems():
  v2 = copy.copy(values)
  v2['week'] = week
  data.push(v2)
newdict = { 'success' : true,
            'data' : data }
json.dumps(newdict)

(Disclaimer: I didn't test this code, but it should give you the basic idea at least)

elbows
  • 219
  • 1
  • 3