在Python中的for循环中创建JSON
我试图做的是创建一个JSON键列表。。。无论如何,我的想法是创建一个列表:在Python中的for循环中创建JSON,python,json,Python,Json,我试图做的是创建一个JSON键列表。。。无论如何,我的想法是创建一个列表: { "Country1": { "bonds": [ {"Bond Name": "Country1 1Y","Prev. Close": 1}, {"Bond Name": "Country1 2Y","Prev. Close": 2} ] }, "Country2": { "bonds": [ {"
{
"Country1":
{
"bonds": [
{"Bond Name": "Country1 1Y","Prev. Close": 1},
{"Bond Name": "Country1 2Y","Prev. Close": 2}
]
},
"Country2":
{
"bonds": [
{"Bond Name": "Country2 1Y","Prev. Close": 1},
{"Bond Name": "Country2 2Y","Prev. Close": 2}
]
}
}
我已经创建的是另一个级别
{
"Countries": [
{
"Argentina": []
}
]
}
这就是我现在的代码,我不知道如何访问嵌套对象
from clear_screen import clear
clear()
import investpy
import json
json_data = {"Countries":[]}
for country_bond_item in investpy.bonds.get_bond_countries():
# Print country name
#print(country_bond_item.title())
# Add value to JSON list eg: 'Argentina'
json_data["Countries"].append({country_bond_item.title():[]})
# Show what we have here
print(json.dumps(json_data, indent=4))
# Loop over country bonds
for country_bond_list_item in investpy.bonds.get_bonds_list(country_bond_item):
# Save JSON value for 'bond name'
bond_json_value = investpy.bonds.get_bond_information(country_bond_list_item, as_json=True)
# eg: {'Bond Name': 'Argentina 1Y', 'Value': '1'}
# Just print value
#print(bond_json_value)
# Save bond data into: eg: json_data["Countries"]["Argentina"]
json_data["Countries"][country_bond_item.title()].append([{'Bond Name': 'Argentina 1Y', 'Value': '1'}])
#print(json.dumps(json_data, indent=4))
不确定为什么索引为:json_data[“Countries”][country_bond_item.title()]不起作用
应该在哪里:json_数据[“国家”][“阿根廷”]-然后我们可以在as列表中添加另一项内容?这只是一个如何生成json的示例。用源代码替换静态数据
导入json
国家=[“a”、“b”、“c”]
债券=[“b1”、“b2”、“b3”]
结果={}
对于国家中的国家:
债券_tmp=[]
对于债券中的债券:
bonds_tmp.append({“Bond Name”:Bond,“Prev.Close”:1})
结果[国家]={“债券”:债券{u tmp}
打印(json.dumps(结果,缩进=4))
印刷品
{
"a": {
"bonds": [
{
"Bond Name": "b1",
"Prev. Close": 1
},
{
"Bond Name": "b2",
"Prev. Close": 1
},
{
"Bond Name": "b3",
"Prev. Close": 1
}
]
},
"b": {
...
}
非常感谢你!在“清理”之后,添加一些注释以解释我最终代码的位置: 注:如果此代码对您有帮助,请向上投票接受答案:)
# Clear screen each time when run script
from clear_screen import clear
clear()
# Import libs
import investpy
import json
# Array for all countries and their bonds
json_data = {}
# Loop over all countries
for country_name in investpy.bonds.get_bond_countries():
# Create 'array' where we can store all bonds for that country
bonds_tmp = []
# Loop over all bonds
for bond_name in investpy.bonds.get_bonds_list(country_name):
# And add them into tmp array
bonds_tmp.append(investpy.bonds.get_bond_information(bond_name, as_json=True))
# Create 'country' item, that will contain array of all bonds above
json_data[country_name.title()] = bonds_tmp
# Break on first item ... for testing!
#break
# Also for testing/debug print value on screen
#print(json.dumps(json_data, indent=4))
# Dump data to file
with open('data.txt', 'w') as outfile:
json.dump(json_data, outfile)