pythonjsonautomationrobotframework

How to read Json data using python?


I have the response message below and code which I follow

result= a["{\"msg\":\"result\",\"id\”:\”test\”,\”result\":{\"categories\":[\"<20M\",\"20M+\",\"50M+\",\"300M+\",\"1G\"],\"series\":[{\"name\":\"Fiber\",\"data\":[216,41,10393,37394,6016]}],\"totals\":{\"<20M\":216,\"20M+\":41,\"50M+\":10393,\"300M+\":37394,\"1G\":6016}}}"]

#Remove a
     sliceresult=result[1:]
    print('Result After slice: {}'.format(sliceresult))
    string_input = ''.join(str(s) for s in sliceresult)
    print(string_input)
    category = json.loads(string_input)['result']['categories']
    series = json.loads(string_input)['result']['series']
    total = json.loads(string_input)['result']['totals']
    print(category, series, total)
    Error Response was:
        category = json.loads(result[1:])['result']['categories']
    TypeError: list indices must be integers, not str

Solution

  • This might help you to begin with:

     a = ["{\"msg\":\"result\",\"id\":\"test\",\"result\":{\"categories\":[\"<20M\",\"20M+\",\"50M+\",\"300M+\",\"1G\"],\"series\":[{\"name\":\"Fiber\",\"data\":[216,41,10393,37394,6016]}],\"totals\":{\"<20M\":216,\"20M+\":41,\"50M+\":10393,\"300M+\":37394,\"1G\":6016}}}"]
    
    string_input = ''.join(str(s) for s in a)
    print(string_input)
    
        category = json.loads(string_input)['result']['categories']
        series = json.loads(string_input)['result']['series']
        total = json.loads(string_input)['result']['totals']
        print(category, series, total)
    

    Also be careful, your input string is not properly formatted. it should be " not