简体   繁体   English

如何在Python中从文件和隐秘读取dict数据到JSON

[英]How to read dict data from file and covert to JSON in Python

I have following data in file. 我的文件中有以下数据。 Getting error while I read and try convert to JSON. 在阅读并尝试转换为JSON时遇到错误。

File(modes.txt) : 文件(modes.txt):

{'status': True, 'mode': 'full'} {'status': False, 'mode': 'half'}

Code: 码:

with open("modes.txt",'r') as f:
   ds = json.dumps(json.load(f))

Error: 错误:

JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1) JSONDecodeError:期望属性名称用双引号引起来:第1行第2列(字符1)

Error is on expected line as file string in files are not double quoted. 错误发生在预期的行上,因为文件中的文件字符串未用双引号引起来。 I could solve the problem replacing single-quote to double-quote. 我可以解决将单引号替换为双引号的问题。 What is good/elegant solution for this scenario? 在这种情况下,什么是好的/优雅的解决方案?

Three issues with your source file's json format (tl;dr: it's not valid json) 源文件的json格式的三个问题(tl; dr:无效的json)

  1. it's a series of dicts, but they aren't in a list, they're bare 这是一系列的命令,但是它们不在列表中,它们只是光秃秃的
  2. True is true in json, same for False which is false json中的TruetrueFalsefalse
  3. As you noted, single vs double quotes. 如您所述,单引号与双引号。

You can get around these problems with the following: 您可以通过以下方法解决这些问题:

import json

ds = list()


with open("modes.txt", 'r') as f:
    for line in f.readlines():
        fixed_line = line.replace('\'', '"').replace("False", "false").replace("True", "true").strip()
        ds.append(json.loads(fixed_line))

This reads each line from your file, very roughly fixes it, and appends it to a list. 这将从文件中读取每一行,非常粗略地对其进行修复,然后将其追加到列表中。 End results is a list of dicts. 最终结果是字典列表。

Please note this code is an example that's meant to demonstrate possible workarounds, don't actually use this in production. 请注意,此代码是一个示例,旨在演示可能的解决方法,请不要在生产中实际使用它。 What if you modes.txt contains escaped doublequotes? 如果您的modes.txt包含转义的双引号怎么办? Or the words True or False within strings? 还是字符串中的TrueFalse单词?

Short answer: you should fix the input file to contain valid json. 简短的答案:您应该修复输入文件以包含有效的json。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM