Config Parser Python - 如何读取 json 文件?
Config Parser Python - How to read from json file?
我在 script/.py
所在的同一文件夹中创建了一个 profile.json
文件。它看起来像:
{
"name": "",
"lastname": "",
"age": "",
"city": "",
}
我希望将它插入到我的脚本中,该脚本获得 headers 个:
"info": {
"given_name": "",
"given_Lastname": "",
"given_age": "",
"given_city": ""
}
我想知道如何才能将我的 profile.json
读入我的脚本?这是我第一次使用它,我也是 Python 的新手。我觉得这可能是一种无需每次都更改代码即可修改信息的简单方法。
编辑:
尝试这样做:
with open('profile.json', encoding='UTF-8') as json_data:
配置 = json.load(json_data)
打印(配置)
然后:
"info":
{
"given_name": config.given_name
}
印刷品说的是很好的信息,但是当涉及到 "given_name" 时:config.given_name 然后我收到一个错误消息
AttributeError: 'dict' object has no attribute 'given_name'
您对原始问题的评论中有一些很好的建议。如果您想从另一个文件中提取可配置数据,您可以通过查看原始问题来执行两个选项。
1.使用 json 文件
这似乎是第一个建议的答案,您可以从这个 JSON 文件配置您可以在程序中使用的变量。假设 config.json 文件在您程序的当前目录中,您可以执行以下操作:
import json
with open('config.json', 'r') as config_file:
config_data = json.load(config_file)
2。使用 python 文件
这是您可以使用的另一个选项,以防您不想在加载配置时反序列化 json。您可以将所有内容都保留为 python 数据类型,因此您只需要导入它。在此示例中,CONFIG_INFO 只是一个字典,您可以将其导入到需要它的其他脚本中。我通常在工作中将其用于 username/password/general 配置。
config.py
CONFIG_INFO: {
"given_name": "test name",
"given_lastname": "test lastname",
"given_age": 12,
"given_city": "Seattle"
}
my_script.py
from config import CONFIG_INFO
print("Config City: {0}".format(CONFIG_INFO["given_city"]))
print("Config Name: {0}".format(CONFIG_INFO["given_name"]))
print("Config Lastname: {0}".format(CONFIG_INFO["given_lastname"]))
print("Config Age: {0}".format(CONFIG_INFO["given_age"]))
问题是您正在尝试将字典键作为属性访问(即:config["given_name"]
与 config.given_name
。您还多次更改了问题,但您是尝试做(我认为)很简单。对于你给出的简单示例,你有一个 json 文件,其中只有一个 json 对象,这可能更接近你尝试做:
*注意:你的json语法错误,应该是{ "info": { ... } }
#!/usr/bin/env python3
'''profile.json:
{
"name": "steve",
"lastname": "jobs",
"age": "70",
"city": "heaven"
}
'''
import json
import io
# Open the JSON File and create a StringIO buffer to hold data
with open('profile.json', 'r') as datafile, io.StringIO() as data:
# Load data into json file
config = json.load(datafile)
# Build json strong
data.write(f'''{{
\r\t"info": {{
\r\t\t"given_name": "{config['name']}",
\r\t\t"given_Lastname": "{config['lastname']}",
\r\t\t"given_age": "{config['age']}",
\r\t\t"given_city": "{config['city']}"
\r\t}}\n}}''')
print(data.getvalue())
# open a new file to save the data (overwrite if it exists)
with open('newfile.json', 'w') as outfile:
# load the json string and dump to outfile
deserialized = json.loads(data.getvalue())
json.dump(deserialized, outfile)
# newfile.json:
#{
# "info": {
# "given_name": "steve",
# "given_Lastname": "jobs",
# "given_age": "70",
# "given_city": "heaven"
# }
#}
这只是你给我的数据的一个简单例子,所以我做了另一个例子,它使用 json 列表而不是 json 字典:
[{
"name": "steve",
"lastname": "jobs",
"age": "70",
"city": "heaven"
},
{
"name": "steve1",
"lastname": "jobs1",
"age": "71",
"city": "heaven1"
},
{
"name": "steve2",
"lastname": "jobs2",
"age": "72",
"city": "heaven2"
},
{
"name": "steve3",
"lastname": "jobs3",
"age": "73",
"city": "heaven3"
},
{
"name": "steve4",
"lastname": "jobs4",
"age": "74",
"city": "heaven4"
}]
还有一个类似的脚本:
#!/usr/bin/env python3
'''profile.json:
'''
import json
import io
# Open the JSON File and create a StringIO buffer to hold data
# Note: StringIO provides a file-like interface over a string
with open('profile.json', 'r') as datafile, io.StringIO() as data:
# Load data into json file
config = json.load(datafile)
# Build json strong
data.write('{\n\t"info": [\n')
#data.write('\t{')
for jsonobj in config:
data.write(f'''\t {{
\r\t\t"given_name": "{jsonobj['name']}",
\r\t\t"given_Lastname": "{jsonobj['lastname']}",
\r\t\t"given_age": "{jsonobj['age']}",
\r\t\t"given_city": "{jsonobj['city']}"
\r\t }}''')
# Note: There is a bug here.
# This will not be able to handle duplicate objects in
# the json list. For a trivial example like this, it works.
if jsonobj == config[-1]:
data.write('\n\t]\n}')
else:
data.write(',\n')
# open a new file to save the data (overwrite if it exists)
with open('newfile.json', 'w') as outfile:
# We need to serialize the json data if we want to write to file
deserialized = json.loads(data.getvalue())
outfile.write(json.dumps(serialized))
# or we can just print it
print(serialized)
我在 script/.py
所在的同一文件夹中创建了一个 profile.json
文件。它看起来像:
{
"name": "",
"lastname": "",
"age": "",
"city": "",
}
我希望将它插入到我的脚本中,该脚本获得 headers 个:
"info": {
"given_name": "",
"given_Lastname": "",
"given_age": "",
"given_city": ""
}
我想知道如何才能将我的 profile.json
读入我的脚本?这是我第一次使用它,我也是 Python 的新手。我觉得这可能是一种无需每次都更改代码即可修改信息的简单方法。
编辑:
尝试这样做:
with open('profile.json', encoding='UTF-8') as json_data: 配置 = json.load(json_data) 打印(配置)
然后:
"info":
{
"given_name": config.given_name
}
印刷品说的是很好的信息,但是当涉及到 "given_name" 时:config.given_name 然后我收到一个错误消息
AttributeError: 'dict' object has no attribute 'given_name'
您对原始问题的评论中有一些很好的建议。如果您想从另一个文件中提取可配置数据,您可以通过查看原始问题来执行两个选项。
1.使用 json 文件
这似乎是第一个建议的答案,您可以从这个 JSON 文件配置您可以在程序中使用的变量。假设 config.json 文件在您程序的当前目录中,您可以执行以下操作:
import json
with open('config.json', 'r') as config_file:
config_data = json.load(config_file)
2。使用 python 文件
这是您可以使用的另一个选项,以防您不想在加载配置时反序列化 json。您可以将所有内容都保留为 python 数据类型,因此您只需要导入它。在此示例中,CONFIG_INFO 只是一个字典,您可以将其导入到需要它的其他脚本中。我通常在工作中将其用于 username/password/general 配置。
config.py
CONFIG_INFO: {
"given_name": "test name",
"given_lastname": "test lastname",
"given_age": 12,
"given_city": "Seattle"
}
my_script.py
from config import CONFIG_INFO
print("Config City: {0}".format(CONFIG_INFO["given_city"]))
print("Config Name: {0}".format(CONFIG_INFO["given_name"]))
print("Config Lastname: {0}".format(CONFIG_INFO["given_lastname"]))
print("Config Age: {0}".format(CONFIG_INFO["given_age"]))
问题是您正在尝试将字典键作为属性访问(即:config["given_name"]
与 config.given_name
。您还多次更改了问题,但您是尝试做(我认为)很简单。对于你给出的简单示例,你有一个 json 文件,其中只有一个 json 对象,这可能更接近你尝试做:
*注意:你的json语法错误,应该是{ "info": { ... } }
#!/usr/bin/env python3
'''profile.json:
{
"name": "steve",
"lastname": "jobs",
"age": "70",
"city": "heaven"
}
'''
import json
import io
# Open the JSON File and create a StringIO buffer to hold data
with open('profile.json', 'r') as datafile, io.StringIO() as data:
# Load data into json file
config = json.load(datafile)
# Build json strong
data.write(f'''{{
\r\t"info": {{
\r\t\t"given_name": "{config['name']}",
\r\t\t"given_Lastname": "{config['lastname']}",
\r\t\t"given_age": "{config['age']}",
\r\t\t"given_city": "{config['city']}"
\r\t}}\n}}''')
print(data.getvalue())
# open a new file to save the data (overwrite if it exists)
with open('newfile.json', 'w') as outfile:
# load the json string and dump to outfile
deserialized = json.loads(data.getvalue())
json.dump(deserialized, outfile)
# newfile.json:
#{
# "info": {
# "given_name": "steve",
# "given_Lastname": "jobs",
# "given_age": "70",
# "given_city": "heaven"
# }
#}
这只是你给我的数据的一个简单例子,所以我做了另一个例子,它使用 json 列表而不是 json 字典:
[{
"name": "steve",
"lastname": "jobs",
"age": "70",
"city": "heaven"
},
{
"name": "steve1",
"lastname": "jobs1",
"age": "71",
"city": "heaven1"
},
{
"name": "steve2",
"lastname": "jobs2",
"age": "72",
"city": "heaven2"
},
{
"name": "steve3",
"lastname": "jobs3",
"age": "73",
"city": "heaven3"
},
{
"name": "steve4",
"lastname": "jobs4",
"age": "74",
"city": "heaven4"
}]
还有一个类似的脚本:
#!/usr/bin/env python3
'''profile.json:
'''
import json
import io
# Open the JSON File and create a StringIO buffer to hold data
# Note: StringIO provides a file-like interface over a string
with open('profile.json', 'r') as datafile, io.StringIO() as data:
# Load data into json file
config = json.load(datafile)
# Build json strong
data.write('{\n\t"info": [\n')
#data.write('\t{')
for jsonobj in config:
data.write(f'''\t {{
\r\t\t"given_name": "{jsonobj['name']}",
\r\t\t"given_Lastname": "{jsonobj['lastname']}",
\r\t\t"given_age": "{jsonobj['age']}",
\r\t\t"given_city": "{jsonobj['city']}"
\r\t }}''')
# Note: There is a bug here.
# This will not be able to handle duplicate objects in
# the json list. For a trivial example like this, it works.
if jsonobj == config[-1]:
data.write('\n\t]\n}')
else:
data.write(',\n')
# open a new file to save the data (overwrite if it exists)
with open('newfile.json', 'w') as outfile:
# We need to serialize the json data if we want to write to file
deserialized = json.loads(data.getvalue())
outfile.write(json.dumps(serialized))
# or we can just print it
print(serialized)