Abdul Rahim
Abdul Rahim

Reputation: 45

Python & Json: Multiline input data into Json

I have a problem regarding my python code that needs to create a multiline JSON type of data.

def get_json_data(response):
 x ={}
 f ={}
 for report in response.get('reports', []):
    columnHeader = report.get('columnHeader', {})
    dimensionHeaders = columnHeader.get('dimensions', [])
    metricHeaders = columnHeader.get('metricHeader', {}).get('metricHeaderEntries', [])
    for row in report.get('data', {}).get('rows', []):
        dimensions = row.get('dimensions', [])
        dateRangeValues = row.get('metrics', [])

        for header, dimension in zip(dimensionHeaders, dimensions):
            x[header.replace('la:','')] = dimension

            for i, values in enumerate(dateRangeValues):
                for metricHeader, value in zip(metricHeaders, values.get('values')):
                    x[metricHeader.get('name').replace('la:','')] = value

        f['dashboard'] = x
        print (json.dumps(f))
 print (json.dumps(f))

Currently, it is showing these data

{
  "dashboard": 
      {"bounces": "12", "userType": "Returning Visitor", "users": "3"}
}

But what I want the output is to display this kind of data

{
 "dashboard": 
     {"bounces": "10", "userType": "New Visitor", "users": "15"},
     {"bounces": "12", "userType": "Returning Visitor", "users": "3"}
}

Upvotes: 3

Views: 147

Answers (3)

Nihal
Nihal

Reputation: 5344

you format should be like this

df1 = {
    "dashboard":
        [{"bounces": "10", "userType": "New Visitor", "users": "15"},
         {"bounces": "12", "userType": "Returning Visitor", "users": "3"}]
}

otherwise it will give error

Upvotes: 2

vipul prajapati
vipul prajapati

Reputation: 293

You cannot build this kind of structure because python does not allow this. Just type this in your terminal you'll get idea about structure error

{
 "dashboard": 
     {"bounces": "10", "userType": "New Visitor", "users": "15"},
     {"bounces": "12", "userType": "Returning Visitor", "users": "3"}
}

Upvotes: 0

Netwave
Netwave

Reputation: 42766

Your output data example is not a valid json, nevertheless this would fix it:

def get_json_data(response):
 x ={}
 f ={'dashboad' : []}
 ...
        f['dashboard'].append(x)
        print (json.dumps(f))
 print (json.dumps(f))

The dashboard value should be a list so then you can append the different x results

Upvotes: 2

Related Questions