且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Python将文本文件转换为JSON格式

更新时间:2023-01-09 20:14:39

您可以将其读取为csv文件并将其转换为json.但是,使用空格作为分隔符时要格外小心,带空格的值应小心处理.否则,请尽可能使用分隔符,代替space.

You can read it as a csv file and convert it into json. But, be careful with spaces as you've used it as separator, the values with spaces should be carefully handled. Otherwise, if possible make the separator , instead of space.

您正在尝试的工作代码,

the working code for what you're trying,

import csv
import json

with open('file.txt', 'rb') as csvfile:
    filereader = csv.reader(csvfile, delimiter=' ')
    i = 0
    header = []
    out_data = []
    for row in filereader:
        row = [elem for elem in row if elem]
        if i == 0:
            i += 1
            header = row
        else:
            row[0:2] = [row[0]+" "+row[1]]
            _dict = {}
            for elem, header_elem in zip(row, header):
                _dict[header_elem] = elem
            out_data.append(_dict)

print json.dumps(out_data)

输出

[
   {
      "Source":"B cells",
      "Target":"Streptococcus",
      "Value":"pneumoniae"
   },
   {
      "Source":"B cells",
      "Target":"Candida",
      "Value":"albicans"
   },
   {
      "Source":"B cells",
      "Target":"Mycoplasma",
      "Value":"120"
   },
   {
      "Source":"B cells",
      "Target":"Neisseria",
      "Value":"111"
   },
   {
      "Source":"B cells",
      "Target":"Pseudomonas",
      "Value":"aeruginosa"
   }
]

更新:刚注意到您需要的json示例更新的问题.希望您可以使用我编写的上述示例来构建它.

UPDATE: Just noticed your updated question with json sample that you require. Hope, you could build it with the above example I've written.