简体   繁体   中英

How to convert text to json format

I have a text file that contains data in json format

{"Header":
{
"name":"test"},
"params":{
"address":"myhouse"
}
}

I am trying to read it from a python file and convert it to json format. I have tried with both yaml and json libraries, and, with both libraries, it converts it to json format, but it also converts the double quotes to single quotes

Is there any way of parsing it into a json format, but keeping the double quotes?

I dont think using a replace call is a valid option, as it will also replace single quotes that are part of the data

Thanks

Do this:

import json
with open("file.json", "r") as f:
    obj = json.load(f)

with open("file.json", "w") as f:
    json.dump(obj, f, indent = 4[, ensure_ascii = False]) # if your string has some unicode characters, let ensure_ascii to be False.

You can use json.load to load a json object from a file.

import json
with open("file.json", "r") as f:
    obj = json.load(f)

The resulting json object delimits strings with ' rather than " , but you can easily use a replace call at that point.

In [6]: obj
Out[6]: {'Header': {'name': 'test'}, 'params': {'address': 'myhouse'}}

EDIT:

Though I misunderstood the question at first, you can use json.dumps to write a string-encoding of the json object that uses double quotes as the standard requires.

In [10]: json.dumps(obj)                                                                       
Out[10]: '{"params": {"address": "myhouse"}, "Header": {"na\'me": "test"}}'

It's unclear what you're trying to do though, as if you're trying to read the json into a Python object, it doesn't matter what string delimiters are used; if you're trying to read your valid json into a Python string, you can just read the file without any libraries.

Thanks Micah. Dump does exactly that

Thanks!

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