Chrome log: Nested dictionary in python

Question:

I’m figuring out how to access to this nested dictionary(it’s a log from chrome)

How Do I access to these keys or at least the ‘method’ and ‘params’ ?
I tried message[method] to get ‘Network.responseReceived’ value but it return an error

def new_file_log(self):
# Chrome log
logs = self.driver.get_log("performance")
    for log in logs:
        message = log["message"]
        if 'Network.responseReceived' in message:
            print(f"{message}")
            # print(f"message['method']")

Error:
print(f"{message[‘method’]}")

TypeError: string indices must be integers

The ‘{message}’ value is what I attached below:

{'message': {'method': 'Network.responseReceived', 'params': {
'frameId': '7592BBC26C81063AFE730881A0DCC64A',
'hasExtraInfo': true,
'loaderId': 'EBDEB728D6E597678DFD4CAA3C91B6B9',
'requestId': '67954.53',
'response': {
    'alternateProtocolUsage': 'unspecifiedReason',
    'connectionId': 0,
    'connectionReused': false,
    'encodedDataLength': 0,
    'fromDiskCache': true,
    'fromPrefetchCache': false,
    'fromServiceWorker': false,
    'headers': {
        'Accept-Ranges': 'bytes',
        'Access-Control-Allow-Origin': '*',
        'Content-Length': '194592',
        'Content-Type': 'video/mp2t',
        'Date': 'Sat, 10 Dec 2022 11:11:48 GMT',
        'ETag': '"638b5585-2f820"',
        'Last-Modified': 'Sat, 03 Dec 2022 13:56:21 GMT',
        'Server': 'nginx',
        'X-Cache-Proxy-Status': 'HIT',
        'X-Cache-Storage-Status': 'HIT',
        },
    'mimeType': 'video/mp2t',
    'protocol': 'http/1.1',
    'remoteIPAddress': 'xx.xx.xx.xxx',
    'remotePort': 443,
    'responseTime': 1.670670708651815e+12,
    'securityDetails': {
        'certificateId': 0,
        'certificateTransparencyCompliance': 'unknown',
        'cipher': 'AES_256_GCM',
        'encryptedClientHello': false,
        'issuer': 'Sectigo RSA Domain Validation Secure Server CA',
        'keyExchange': '',
        'keyExchangeGroup': 'X25519',
        'protocol': 'TLS 1.3',
        'sanList': ['*.scws-content.net', 'scws-content.net'],
        'serverSignatureAlgorithm': 2052,
        'signedCertificateTimestampList': [],
        'subjectName': '*.scws-content.net',
        'validFrom': 1668211200,
        'validTo': 1702511999,
        },
    'securityState': 'secure',
    'status': 200,
    'statusText': 'OK',
    'timing': {
        'connectEnd': -1,
        'connectStart': -1,
        'dnsEnd': -1,
        'dnsStart': -1,
        'proxyEnd': -1,
        'proxyStart': -1,
        'pushEnd': 0,
        'pushStart': 0,
        'receiveHeadersEnd': 0.474,
        'requestTime': 40578.614259,
        'sendEnd': 0.07,
        'sendStart': 0.07,
        'sslEnd': -1,
        'sslStart': -1,
        'workerFetchStart': -1,
        'workerReady': -1,
        'workerRespondWithSettled': -1,
        'workerStart': -1,
        },
    'url': 'https://xx-xx-xx.xxxx-content.net/hls/16/c/d7/c0702020-a0b0-0800-a02d-507000080d2b/video/720p/0000-0250.ts',

EDIT 1 :
Every String starts with:

[{'level': 'INFO', 'message': '{"message": {'method': ....
logs = json.loads(self.driver.get_log("performance")) # TypeError: the JSON object must be str, bytes or bytearray, not list

or

print(f"{log['message'].keys()}") # AttributeError: 'str' object has no attribute 'keys'

print(f"{log.keys()}") #  dict_keys(['level', 'message', 'timestamp'])

EDIT 2:
I’ve found this solution. I don’t know if it’s the best

    def new_file_log(self):
    logs = self.driver.get_log("performance")

    for log in logs:
        message = json.loads(log["message"])["message"]
        if "Network.responseReceived" == message["method"]:
            print(f"{message['method']}")
            print(f"{message['params']}")
            print(f"{message['params']['response']['url']}")

            print(' ')
Asked By: ghost239

||

Answers:

This is in json format (very similar syntax to python data types), you should try:

logs = json.loads(self.driver.get_log("performance"))

Answered By: LarsJaeger

Just Reproduce your code here. Can you try something like this.?

with open('stack.json') as stack:
    st =  json.load(stack)
    out=  st.get('message')['method']
    if 'Network.responseReceived' in out:
        print(f"{message}")

Just using dummy json to give you a hint
Stack.json

{
    "message": {
        "method": "Network.responseReceived",
        "params": {
        }
}

}

Answered By: Deepak Mourya
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.