【问题标题】:how I can convert a text file to json with the given keys?如何使用给定的键将文本文件转换为 json?
【发布时间】:2021-04-18 10:52:50
【问题描述】:

我有一个这样的文本文件:

[{"Keywords":"softeware developer","Results":[{"categoryId":"1234","categoryName":"lead developer","score":"0.7412536859512329"},{"categoryId":"1657","categoryName":"developer consultant","score":"0.6560295867919922"},{"categoryId":"2324","categoryName":"etl developer","score":"0.6531170797348023"},{"categoryId":"2632","categoryName":"oracle developer","score":"0.6264872598648071"},{"categoryId":"1232","categoryName":"sharepoint developer","score":"0.6262540578842163"}]}]

我想知道我可以使用以下键将其转换为 Jason 文件吗? Keywords , Results

如果我可以将结果分开将是完美的。如果没有,没关系。

【问题讨论】:

    标签: python json file txt


    【解决方案1】:

    不是 python 方法,但您可以在终端上使用jq

    cat file.txt | jq "." > file.json
    

    把它们分开

    cat file.txt | jq ".[].Keywords" > keywords.json
    cat file.txt | jq ".[].Results" > results.json
    

    (这将适用于数组中的每个条目,如果您只想要一个添加索引,例如jq ".[0].Keywords

    【讨论】:

      【解决方案2】:
      >>> import json
      >>> with open('$path_to_file') as f: j = json.load(f)
      >>> jk = j[0]['Keywords']
      >>> jr = j[0]['Results']
      >>> with open('k.txt', 'w') as f: json.dump({'Keywords':jk},f)
      >>> with open('r.txt', 'w') as f: json.dump({'Results':jr},f)
      

      【讨论】:

        【解决方案3】:

        试试

        import json
        with open("file.txt", "rb") as f:
            content = json.load(f)
        with open("fileJson.txt", "wb") as fout:
            json.dump(content, fout, indent=1)
        

        或访问Text to Json获取答案

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-12-06
          • 2022-01-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-12-22
          • 1970-01-01
          相关资源
          最近更新 更多