[英]How to display json content for every \n on a new line in python
I have this output from a file我从文件中有这个 output
file = open('path', 'r')
file_content = file.read()
file_content =
123
123
123
I'm creating the following json to serve as reply for a api using flask:我正在使用 flask 创建以下 json 作为 api 的回复:
var = file_content
return jsonify({'result':var})
The curl output is curl output 是
123\n123\n123\n
Is there a way to make the json display as such, every single "123" on a new line and the '\n' removed?有没有办法让 json 像这样显示,每一个“123”都在一个新的行上,并且“\n”被删除? :
:
{result: '123
123
123'
Even an article would be good to guide me on how to accomplish this, basically I want to prittyprint the response..即使是一篇文章也能很好地指导我如何做到这一点,基本上我想把回复打印出来..
flask code as reference: 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()})
You can "display" each line separately by splitting the lines into a list.您可以通过将行拆分为列表来分别“显示”每一行。 Here is an example:
这是一个例子:
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))
Input (data.txt):输入(data.txt):
these
are
multiple
lines
Output: Output:
{
"lines": [
"these",
"are",
"multiple",
"lines"
]
}
Here is some background on multiple ways python prints strings:以下是 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: Output:
these
are
multiple
lines
{'lines': 'these\nare\nmultiple\nlines'}
{
"lines": [
"these",
"are",
"multiple",
"lines"
]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.