python - 使用 Python 从 .txt 文件中创建 JSON
问题描述
这是 txt 文件中的数据(制表符分隔):
President, U.S. Vote For 1 0 of 1,599 precincts reporting
Candidate Party Votes
Deval Patrick DEM 0
Bernie Sanders DEM 0
Joseph R. Biden DEM 0
Michael R. Bloomberg DEM 0
Elizabeth Warren DEM 0
Pete Buttigieg DEM 0
Tom Steyer DEM 0
Andrew Yang DEM 0
Michael Bennet DEM 0
John K. Delaney DEM 0
Tulsi Gabbard DEM 0
Cory Booker DEM 0
这是我要创建的 JSON 的架构:
"races": [ {
"name": "President, U.S.",
"reference_id": "US-President",
"election_date": "2020-03-17",
"market": "balt",
"state_postal": "MD",
"reporting_units": [
{
"name": "US",
"level": "fed",
"state_postal": "MD",
"precincts_reporting": 0,
"total_precincts": 1599,
"data_source_update_time": "2020-02-25T19:54:23+0000",
"candidates": [
{
"last_name": "Patrick",
"middle_name":null,
"first_name":"Deval",
"party": "DEM",
"vote_count": 0,
}, ...
]
}
]
}
]
因此candidates
,每个候选对象都必须存在该对象,并且races
txt 文件中包含更多对象。我知道我会使用json.dumps
它,但我真的在努力解决如何处理这个文本文件的每一行的语法。
解决方案
如果您的源文件是常规的,您可能需要考虑逐行解析文件以将其读入 python:
with open(path_to_file, 'r') as f:
# Loop through each line;
# Separate logic for parsing 1st line and subsequent lines,
# along with any other cases you have to consider
推荐阅读
- c++ - unordered_map 对哈希函数的过度调用
- android - 无法在我的应用程序中集成缩放
- javascript - CodeMirror 突出显示特定的正则表达式匹配
- javascript - 提交尝试失败后保持模式表单打开
- python - Google Analytics API 仅返回“google / cpc”作为媒介?
- python - 将年份设置为 matplotlib 中的 x 标签
- sql-server-2008 - SQL 数据库 cpu 100% 利用率
- html - 让带有标题的图像自动调整 Wordpress 中不同屏幕的大小
- mongodb - MongoDB $lookup 仅替换对象数组中的 ID
- gitlab - linux shell gitlab-runner 如何访问 vpn 后面的服务器?