3

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"}
}
0

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank man. You are the great. Thank for help to solve my problem
2

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

2 Comments

thank for the help on structure error. but this not the answer
yes, i know. answer was given by netwave already. and i don't want to post the same thing
0

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"}
}

1 Comment

Owh thank for emphasis on structure error for json code thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.