Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"}
}
like image 789
Abdul Rahim Avatar asked Apr 12 '26 07:04

Abdul Rahim


1 Answers

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

like image 65
Netwave Avatar answered Apr 14 '26 22:04

Netwave



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!