将内容从文本文件转换为对象列表 python
Converting xontent from text file to list of objects python
我有cookie.txt,内容如下
[
{
"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"
}
]
我正在尝试访问该 txt 的每个对象,如下所示
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)
但似乎print(cookie)
有完整的内容。
如何访问 {}
中的每个对象?
我应该可以像这样访问它们 cookie.get('name', '')
, cookie.get('value', '')
您可以简化您的代码,即使它已经有效...
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'
为什么要先将列表转换为大字符串?您可以直接使用 json.load
而不是 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
我有cookie.txt,内容如下
[
{
"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"
}
]
我正在尝试访问该 txt 的每个对象,如下所示
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)
但似乎print(cookie)
有完整的内容。
如何访问 {}
中的每个对象?
我应该可以像这样访问它们 cookie.get('name', '')
, cookie.get('value', '')
您可以简化您的代码,即使它已经有效...
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'
为什么要先将列表转换为大字符串?您可以直接使用 json.load
而不是 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