【问题标题】:Converting strings separated by comma in text files to JSON将文本文件中以逗号分隔的字符串转换为 JSON
【发布时间】:2017-01-25 09:04:12
【问题描述】:

我在将文本文件中的字符串转换为 JSON 格式时遇到问题。现在我有 3 个文本文件,在每个文件中,文件中有很多行我想转换为 JSON 格式的对象。

字符串用分号隔开,如下所示:

mary; 24; female;1993; student
john; 21; male; 1982; student
luke; 22; male; 1988; student

如何将这些转换为 JSON 格式?

我尝试使用 json.loads() 但它不起作用。非常感谢您的帮助。

【问题讨论】:

  • 你的 JSON 的结构是什么? json.loads() 在您的数据为标准 JSON 格式的情况下提供帮助。文件格式看起来更像csvjson.loads() 在这里没有意义
  • 您希望生成的 JSON 表示哪种数据结构?字符串列表?

标签: python json string parsing


【解决方案1】:

您的文本文件不是JSON 格式,因此json.loads() 将不起作用。像这样的东西可以帮助将其转换为 JSON:

$ cat a.txt
mary; 24; female;1993; student
john; 21; male; 1982; student
luke; 22; male; 1988; student

$ cat a.py
import json
arr = []
with open('a.txt', 'r') as f:
    for line in f:
      # split around semicolon and then strip spaces from the ends
      fields = map(lambda s: s.strip(), line.split(';'))
      arr.append({
          "name": fields[0],
          "age": int(fields[1]),
          "gender": fields[2],
          "year": int(fields[3]),
          "occupation": fields[4],
      })
print json.dumps(arr, indent=2)

$ python a.py
[
  {
    "gender": "female",
    "age": 24,
    "occupation": "student",
    "name": "mary",
    "year": 1993
  },
  {
    "gender": "male",
    "age": 21,
    "occupation": "student",
    "name": "john",
    "year": 1982
  },
  {
    "gender": "male",
    "age": 22,
    "occupation": "student",
    "name": "luke",
    "year": 1988
  }
]

我使用json.dumps() 从 Python 数据结构(在本例中为字典列表)获取 JSON 编码的字符串。

【讨论】:

  • 一个字典列表 :)
  • 啊,是的。对不起,当然。切换语言会对你这样做:))
  • 嗨@Vlad 我试过了,但我有这个错误:描述符'strip'需要'str'对象但收到'unicode'
  • 我以为他们是普通的strings。我已经将该位从str.strip 编辑为lambda s: s.strip(),它在收到的任何内容上调用strip()。这在这两种情况下都应该有效。
【解决方案2】:

由于您的数据的每一行似乎都包含字符分隔值,因此使用 Python csv 模块将是一种合乎逻辑的读取方式,尤其是因为 csv.DictReader 会将每一行作为字典返回,这在以下情况下非常方便需要将该数据转换为 JSON 格式。

import csv
import json
import sys

def open_csv(filename, mode='r'):
    """Open a csv file in proper mode depending on Python verion."""
    return(open(filename, mode=mode+'b') if sys.version_info[0] == 2 else
           open(filename, mode=mode, newline=''))

json_objects = []
fields = 'name age gender year occupation'.split()
with open_csv('records.txt', 'r') as file:
    reader = csv.DictReader(file, fieldnames=fields, delimiter=';', skipinitialspace=True)
    for row in reader:
        json_objects.append(row)

print(json.dumps(json_objects))

输出:

[{"gender": "female", "age": "24", "occupation": "student", "name": "mary", "year": "1993"}, {"gender": "male", "age": "21", "occupation": "student", "name": "john", "year": "1982"}, {"gender": "male", "age": "22", "occupation": "student", "name": "luke", "year": "1988"}]

【讨论】:

    猜你喜欢
    • 2019-04-05
    • 2019-11-18
    • 2020-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-16
    相关资源
    最近更新 更多