简体   繁体   中英

How to display json content for every \n on a new line in python

I have this output from a file

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:

var = file_content 
return jsonify({'result':var})

The curl output is

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? :

{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:

    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):

these
are
multiple
lines

Output:

{
    "lines": [
        "these",
        "are",
        "multiple",
        "lines"
    ]
}

Here is some background on multiple ways python prints strings:

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"
    ]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM