Home > front end >  Converting xontent from text file to list of objects python
Converting xontent from text file to list of objects python

Time:05-16

I have cookie.txt with content like below

[
    {
        "domain": "example.com",
        "expirationDate": 1683810439,
        "hostOnly": false,
        "httpOnly": false,
        "name": "__adroll_fpc",
        "path": "/",
        "sameSite": "lax",
        "secure": false,
        "session": false,
        "storeId": null,
        "value": "2123213-1651041941056"
    },
    {
        "domain": "example.com",
        "expirationDate": 1715324838,
        "hostOnly": false,
        "httpOnly": false,
        "name": "_ga",
        "path": "/",
        "sameSite": null,
        "secure": false,
        "session": false,
        "storeId": null,
        "value": "12332.1651041940"
    }
]

I'm trying to access each object of that txt like below

def initCookies(self):
        with open('cookie.txt', encoding='utf8') as f:
            cookies = f.readlines()
        mystring = ' '.join([str(item) for item in cookies])

        data = json.loads(mystring)
        print(type(data))

        for cookie in data:
            print(cookie)

but it seems print(cookie) has the whole content.

how to access each object within {} ?

I should be able to access them like this cookie.get('name', ''), cookie.get('value', '')

CodePudding user response:

You can simplify your code, even though it already works...

import json
with open('cookie.txt', encoding='utf8') as f:
  cookies = json.load(f)
for cookie in cookies:
  print(cookie.get("name"))  # '__adroll_fpc', '_ga'

CodePudding user response:

why you convert the list to a big string first ? You could just do it directly with json.load instead of json.loads

with open('cookie.txt', encoding='utf8') as f:
    data = json.load(f)
   
data # list of 2 dictionaries

for dic in data:
    print(dic.get('name'))

Output:
__adroll_fpc
_ga

  • Related