我在将文本文件中的字符串转换为JSON格式时遇到问题。现在我有3个文本文件,在每个文件中,文件中有很多行要转换为JSON格式。
字符串用分号分隔,如下所示:
mary; 24; female;1993; student
john; 21; male; 1982; student
luke; 22; male; 1988; student
如何将这些转换为JSON格式?
我尝试使用json.loads()但它不起作用。非常感谢您的帮助。
答案 0 :(得分:4)
您的文字文件不是JSON格式,因此<gradient
android:centerColor="@color/ColorTwoBackground"
android:endColor="@color/ColorTwoForeground"
android:gradientRadius="400"
android:startColor="@color/ColorTwoBackground"
android:type="radial" >
</gradient>
无法使用。这样的东西可以帮助将它转换为JSON:
# Import
import numpy as np
import matplotlib.pyplot as plt
# Generate random normally distributed data
data=np.random.randn(10000)
# Histogram
heights,bins = np.histogram(data,bins=50)
# Normalize
heights = heights/float(sum(heights))
binMids=bins[:-1]+np.diff(bins)/2.
plt.plot(binMids,heights)
我使用json.loads()
从Python数据结构中获取JSON编码的字符串(在本例中为字典列表)。
答案 1 :(得分:0)
由于数据的每一行似乎都包含字符分隔值,因此使用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"}]