【问题标题】:Dump to JSON adds additional double quotes and escaping of quotes转储到 JSON 添加额外的双引号和引号转义
【发布时间】:2014-10-04 05:19:04
【问题描述】:

我正在使用 Python 工具检索 Twitter 数据,并将这些数据以 JSON 格式转储到我的磁盘中。我注意到一条用双引号括起来的推文意外转义了整个数据字符串。此外,实际 JSON 格式的所有双引号都用反斜杠转义。

它们看起来像这样:

"{\"created_at\":\"8 月 8 日星期五 11:04:40 +0000 2014\",\"id\":497699913925292032,

如何避免这种情况?应该是:

{"created_at":"Fri Aug 08 11:04:40 +0000 2014" .....

我的文件输出代码如下所示:

with io.open('data'+self.timestamp+'.txt', 'a', encoding='utf-8') as f:
            f.write(unicode(json.dumps(data, ensure_ascii=False)))
            f.write(unicode('\n'))

在后续处理步骤中读取 JSON 文件时,意外转义会导致问题。

【问题讨论】:

    标签: python json


    【解决方案1】:

    解决这个问题的简单方法是在转储之前使用 json 加载函数,如下所示:

    import json
    data = json.loads('{"foo": json.dumps([{"bar": 1}, {"baz": 2}])}')
    with open('output.json','w') as f:
       json.dump(data,f,indent=4)
    
    

    【讨论】:

      【解决方案2】:

      为了其他有类似问题的人,我用它来将 JSON 格式的数据转储到数据来自 API 调用的文件中。下面只是一个指示性示例,根据您的要求进行更新

      import json
      
      # below is an example, this came for me from an API call
      json_string = '{"address":{"city":"NY", "country":"USA"}}'
      
      # dump the JSON data into file ( dont use json.dump as explained in other answers )
      with open('direct_json.json','w') as direct_json:    
          direct_json.write(json_string)
          direct_json.write("\n")
      
      # load as dict
      json_dict = json.loads(json_string)
      
      # pretty print
      print(json.dumps(json_dict, indent = 1)) 
      
      # write pretty JSON to file
      with open('formatted.json','w') as formatted_file: 
          json.dump(json_dict, formatted_file, indent=4)  
      

      【讨论】:

        【解决方案3】:

        另一种可能发生这种不需要的转义的情况是,如果您尝试在 json.dumps() 的预处理输出上使用 json.dump()。例如

        import json, sys
        json.dump({"foo": json.dumps([{"bar": 1}, {"baz": 2}])},sys.stdout)
        

        会导致

        {"foo": "[{\"bar\": 1}, {\"baz\": 2}]"}
        

        为避免这种情况,您需要传递字典而不是 json.dumps() 的输出,例如

        json.dump({"foo": [{"bar": 1}, {"baz": 2}]},sys.stdout)
        

        输出想要的

        {"foo": [{"bar": 1}, {"baz": 2}]}
        

        (你问为什么要用 json.dumps() 预处理内部列表?嗯,我有另一个函数用其他东西创建内部列表,我认为返回一个来自该函数的 json 对象...错误。)

        【讨论】:

          【解决方案4】:

          您正在对 JSON 字符串进行双重编码。 data已经是一个 JSON 字符串,不需要再次编码

          >>> import json
          >>> not_encoded = {"created_at":"Fri Aug 08 11:04:40 +0000 2014"}
          >>> encoded_data = json.dumps(not_encoded)
          >>> print encoded_data
          {"created_at": "Fri Aug 08 11:04:40 +0000 2014"}
          >>> double_encode = json.dumps(encoded_data)
          >>> print double_encode
          "{\"created_at\": \"Fri Aug 08 11:04:40 +0000 2014\"}"
          

          只需将这些直接写入您的文件即可:

          with open('data{}.txt'.format(self.timestamp), 'a') as f:
              f.write(data + '\n')
          

          【讨论】:

          • f.write(data + '\n') -- 与 -- data = encoded_data -- 来自您的示例相关。
          • @RichElswick OP 使用变量 data,其中包含已编码的 JSON 数据,所以是的,我使用变量名称 encoded_data 来说明发生了什么。
          猜你喜欢
          • 2013-08-09
          • 2017-01-14
          • 1970-01-01
          • 2020-11-26
          • 1970-01-01
          • 2011-06-13
          • 2013-06-30
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多