首页 > 解决方案 > 使用 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,每个候选对象都必须存在该对象,并且racestxt 文件中包含更多对象。我知道我会使用json.dumps它,但我真的在努力解决如何处理这个文本文件的每一行的语法。

标签: pythonjsonpython-2.7csv

解决方案


如果您的源文件是常规的,您可能需要考虑逐行解析文件以将其读入 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

推荐阅读