[英]How to display json content for every \n on a new line in python
我從文件中有這個 output
file = open('path', 'r')
file_content = file.read()
file_content =
123
123
123
我正在使用 flask 創建以下 json 作為 api 的回復:
var = file_content
return jsonify({'result':var})
curl output 是
123\n123\n123\n
有沒有辦法讓 json 像這樣顯示,每一個“123”都在一個新的行上,並且“\n”被刪除? :
{result: '123
123
123'
即使是一篇文章也能很好地指導我如何做到這一點,基本上我想把回復打印出來..
flask 代碼作為參考:
from flask import Flask, jsonify, request
import start, tempData
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
@app.route('/test<int:num>', methods=['GET'])
def callMainF(num):
start.cicleInfotypes(num)
return jsonify({'result':tempData.getOuput()})
您可以通過將行拆分為列表來分別“顯示”每一行。 這是一個例子:
import json
def open_txt(path):
with open(path, 'r') as file:
return file.readlines() # return a list of lines
# lines = open_txt('./data.txt') # uncomment if you want \n character at the end of lines
lines = [line.replace('\n', '') for line in open_txt('./data.txt')] # remove the \n character
# put it into a dict and prettify the output
print(json.dumps({'lines': lines}, indent=4))
輸入(data.txt):
these
are
multiple
lines
Output:
{
"lines": [
"these",
"are",
"multiple",
"lines"
]
}
以下是 python 打印字符串的多種方式的一些背景知識:
import json
lines = 'these\nare\nmultiple\nlines'
print(lines)
print({'lines': lines})
print(json.dumps({'lines': [line for line in lines.split('\n')]}, indent=4))
Output:
these
are
multiple
lines
{'lines': 'these\nare\nmultiple\nlines'}
{
"lines": [
"these",
"are",
"multiple",
"lines"
]
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.