0

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()})
8
  • if the f variable in f.read() an opened file? Commented May 11, 2020 at 13:22
  • Yup, didn't thought to include it, will edit asap. Commented May 11, 2020 at 13:23
  • I don't think json lets you have a newline inside a string. Do you just want the output format to be prettier? Commented May 11, 2020 at 13:27
  • Yeah basically, I wanna have 1 tag and the tag.text to be a string, which i want to be formatted basically, because at the moment it generates a 1000 character line which is very hard to read. Commented May 11, 2020 at 13:31
  • Like copying a text from a book page and do something like, {'bookpage1': 'AllTheTextFromAPage'} Commented May 11, 2020 at 13:32

1 Answer 1

1

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"
    ]
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.