Juan Medina
Juan Medina

Reputation: 154

Why this '/' in my json

I have this

import json

header = """{"fields": ["""

print(header)

with open('fields.json', 'w') as outfile:
    json.dump(header, outfile)

and the return of print it's ok:

{"fields": [

but what is in the fields.json it's

"{\"fields\": ["

Why and how can I solve it?

Thanks

Upvotes: 2

Views: 837

Answers (3)

Max Alibaev
Max Alibaev

Reputation: 690

First of all, it's not /, it's \.

Second, it's not in your JSON, because you don't really seem to have a JSON here, you have just a string. And json.dump() converts the string into a string escaped for JSON format, replacing all " with \".

By the way, you should not try to write incomplete JSON as a string yourself, it's better just to make a dictionary {"fields":[]}, then fill it with all values you want and later save into file through json.dump().

Upvotes: 1

Shiva Kishore
Shiva Kishore

Reputation: 1701

The JSON you are trying to write is bring treated as a string
so " is converted to \" . to avoid that we need to decode json using json.loads() before writing to file
The json should be complete or else json.loads() will throw an error

import json

header = """{"name":"sk"}"""
h = json.loads(header)
print(header)

with open('fields.json', 'w') as outfile:
    json.dump(h, outfile)

Upvotes: 1

somesingsomsing
somesingsomsing

Reputation: 3350

There is no issue there. The \ in the file is to escape the ". To see this read the json back and print it. So to add to your code

import json

header = """{"fields": ["""

print(header)

with open('C:\\Users\\tkaghdo\\Documents\\fields.json', 'w') as outfile:
    json.dump(header, outfile)

with open('C:\\Users\\tkaghdo\\Documents\\fields.json') as data_file:
    data = json.load(data_file)

print(data)

you will see the data is printed as {"fields": [

Upvotes: 1

Related Questions