Python 转储 "\n"而不是 json 文件中的换行符

标签 python json newline pretty-print

我一直在通过 facebook 的 Graph API 获取一些数据,并将其以 json 格式保存在一个新文件中。但是,每当我尝试将其保存在文件中时,新行实际上并不显示为换行符,而是显示为“\n”。此外,在任何数据之前还会附加一个反斜杠。

例如,

我希望数据以这种格式保存:

{
"feed": {
"data": [
{
"message": "XYZ",
"created_time": "0000-00-0000:00:00+0000",
"id": ABC"
}

但它是以这种格式保存的(在一行中)

"{\n\"feed\": {\n\"data\": [\n{\n\"message\": \"XYZ\",\n\"created_time\": \"0000-00-0000:00:00+0000\",\n\"id\": \"ABC\"\n}

如何将其保存为第一种格式而不是第二种格式?

我一直在使用这段代码:

url2 = '{0}?fields={1}&access_token={2}'.format(url,fields,token) #the format in which the API receives the request to get the data which is needed
# token is the access token, url is to connect to fb and fields is the data I want
size = os.path.getsize('new.json') #gets the size of the file 
content = requests.get(url2).json()  #obtaining the content 
obj = json.dumps(content,indent = 4) 

with open('new.json','r+') as f:    #if file size is 0, delete all content and rewrite with new and old content 
    if size>0:
        f.truncate(0)
    json.dump(obj,f)

尽管我使用了缩进,但它并没有按照我想要的方式漂亮地打印。感谢帮助!

最佳答案

您正在使用 json.dumps 创建数据的 JSON 表示形式。然后,您使用 json.dump 创建该表示形式的 JSON 表示形式。你正在双重 JSON化它。只需使用其中之一即可。

关于Python 转储 "\n"而不是 json 文件中的换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56910059/

相关文章:

javascript - 通过缩短变量名来减少 json 字符串的大小

c - 如何使用 C 程序检测任何文件的新行

python - 由于 gunicorn, Airflow 启动失败

python - 如何在 python Flask-peewee 中反转外键

javascript - 多个 GET 请求与返回多个对象的一个​​ GET 请求

html - 使用 AngularJS 在 HTML 中添加换行符

java - 如何在文本/纯 servlet 响应中换行

python - GAE/Python - 将请求从 Controller 传递到模型的最佳方式是什么?

python - 如何在 Tensorflow 训练期间打印梯度?

json - 将XmlSlurper GPathResult转换为JSON字符串