3

我正在尝试读取具有制表符和换行符等的文件,并且数据是 JSON 格式。

当我使用file.read()/readlines()等阅读它时,所有的换行符和制表符也会被读取。

我试过rstrip(),分裂等但徒劳无功,也许我错过了一些东西:

这基本上是我正在做的事情:

 f = open('/path/to/file.txt')
 line = f.readlines()
 line.split('\n')

这是数据(包括原始选项卡,因此格式很差):

        {
      "foo": [ {
       "id1" : "1",
   "blah": "blah blah",
       "id2" : "5885221122",
      "bar" : [
              {  
         "name" : "Joe JJ", 
          "info": [                 {
         "custid": "SSN",    
         "type" : "String",             }        ]
        }     ]     }     ]  }

我想知道我们是否可以优雅地忽略它。

也希望能用json.dumps()

4

6 回答 6

6

如果数据是 json,为什么不直接使用 json.load() 呢?

import json
d = json.load(open('myfile.txt', 'r'))
于 2011-07-26T22:34:29.053 回答
1

我猜有点hack,效率低下:

f = open("/path/to/file.txt")
lines = f.read().replace("\n", "").replace("\t", "").replace(" ", "")

print lines
于 2011-07-26T22:36:28.773 回答
0
$ cat foo.json | python -mjson.tool
Expecting property name: line 11 column 41

逗号"type" : "String",导致 JSON 解码器阻塞。如果不是这个问题,您可以使用json.load()直接加载文件。

换句话说,您的 JSON 格式不正确,这意味着您需要先执行替换操作,然后再将其提供给json.loads(). 由于无论如何您都需要将文件完全读入字符串才能执行替换操作,因此请使用以下命令json.loads(jsonstr)代替json.load(jsonfilep)

    >>> import json, re
    >>> jsonfilep = open('foo.json')
    >>> jsonstr = re.sub(r'''(["'0-9.]\s*),\s*}''', r'\1}', jsonfilep.read())
    >>> jsonobj = json.loads(jsonstr)
    >>> jsonstr = json.dumps(jsonobj)
    >>> print(jsonstr)
    {"foo": [{"blah": "blah blah", "id2": "5885221122", "bar": [{"info":
    [{"type": "String", "custid": "SSN"}], "name": "Joe JJ"}], "id1": "1"}]}

我只使用了该re模块,因为它可能发生在任何值、数字或字符串上。

于 2011-07-26T23:24:46.017 回答
0

这种结构是从哪里来的?节哀顺变。无论如何,作为一个开始,你可以试试这个:

cleanedData = re.sub('[\n\t]', '', f.read())

这是对换行符和制表符的强力删除。它返回的可能适合喂入json.loads. 一旦清除了额外的空格和换行符,这将很大程度上取决于文件的内容是否实际上是有效的 JSON。

于 2011-07-26T22:33:09.300 回答
0

如果你想遍历每一行,你可以:

for line in open('path/to/file.txt'):
  # Remove whitespace from both ends of line
  line = line.strip()

  # Do whatever you want with line
于 2011-07-26T22:35:31.457 回答
0

json模块的用法呢?

import json

tmp = json.loads(open("/path/to/file.txt", "r"))

output = open("/path/to/file2.txt", "w")
output.write(json.dumps(tmp, sort_keys=True, indent=4))
于 2011-07-26T22:37:27.283 回答