如何将以下文本文件读取为json



文件:

random_seed: 42
dataset_config {
data_sources {
abc: "xyz"
def: "qwerty"
}
}

我试过了:

import json
import ast
with open(raw_data) as f:
data = f.read()
data = data.splitlines()
def Convert(a):
it = iter(a)
res_dct = dict(zip(it, it))
return res_dct
data = Convert(data)
print(data)

我得到的:{'random_seed:42':'dataset_config{','data_sources{':'abc:"xyz"','def:"qwerty"':"}"}

我认为,这是因为您使用的文本文件没有有效的JSOn格式。你也许可以试试这样的东西:

import json
# Parsing the text file and storing it in a dictionary
data = {}
current_key = None
current_dict = None
with open(raw_data) as f:
for line in f:
if '{' in line:
# Start a new dictionary
current_dict = {}
data[current_key] = current_dict
elif '}' in line:
# End the current dictionary
current_dict = None
current_key = None
else:
# Split the line into a key and value
key, value = line.strip().split(': ')
if current_dict is not None:
# Add the key-value pair to the current dictionary
current_dict[key] = value
else:
# Save the key for the next dictionary
current_key = key
# Converting the dictionary to a JSON string
json_data = json.dumps(data)
# Looading the JSON string into a Python object
json_obj = json.loads(json_data)
#Finallly printing it
print(json_obj)

更新时间:

好的,现在让我们试着把引号放在关键和视频博客上。

import json
import re
# opening the text file and read the contents into a string
with open('text_file.txt', 'r') as f:
text = f.read()
# sarting an empty dictionary to store the parsed data
json_data = {}
# breaking the text into lines
lines = text.split('n')
# looping through each line
for line in lines:
# Match lines with key-value pairs
match = re.match(r'^(w+):(.+)$', line)
if match:
# Extract the key and value from the match
key = match.group(1)
value = match.group(2)
# parsing the value as a JSON object if it is surrounded by curly braces
if value.startswith('{') and value.endswith('}'):
# Fixing the value to be in valid JSON format by adding quotes around the keys and values
fixed_value = re.sub(r'(w+):', '"\1":', value)
value = json.loads(fixed_value)
# adding the key-value pair to the dictionary
json_data[key] = value
# Converting the dictionary to a JSON object
json_obj = json.dumps(json_data)

相关内容

  • 没有找到相关文章

最新更新