user411103
user411103

Reputation:

Saving python variable with new lines in JSON with pretty print

I am reading this text from a CSV file in Python.

Hi there,



This is a test.

and storing it into a variable text.

I am trying to write this variable in a JSON file with json.dump(), but it is being transformed into:

' \ufeffHi there,\n\n\xa0\n\nThis is a test.

How can I make my JSON file look like the one below?:

{
  "text": "Hi there,



    This is a test."
}

Upvotes: 0

Views: 928

Answers (2)

Takiro
Takiro

Reputation: 470

Well it can be done, as user1308345 shows in his answer but it wouldn't be valid JSON anymore and you probably run into issues later, when deserializing the JSON.

But if you really want to do it, and still want to have valid JSON, you could split the string (and remove the new lines) and serialize them as an array like suggested in this answer https://stackoverflow.com/a/7744658/1466757

Then your JSON would look similar to this

{
 "text": [
    "Hi there,",
    "",
    "",
    "",
    "this is a test."
  ]
}

After deserializing it, you would have to put the line breaks back in.

Upvotes: 1

user1308345
user1308345

Reputation: 1112

JSON does not allow real line-breaks. If you still want to use them, you will have to make your own "json" writer.

Edit: Here's function that will take python dict (which you can get using json.loads() ) and print it the way you need:

def print_wrong_json(dict_object):
    print '{'
    print ',\n'.join(['"{}": "{}"'.format(key, dict_object[key]) for key in dict_object])
    print '}'

Upvotes: 1

Related Questions