Reputation: 121
I have a dictionory with key value pair in single inverted commas as follows:
filename = 'sub-310621_task-EMOTION_acq-LR_bold.nii.gz'
intended_for ={"IntendedFor", filename}
AS i am want to write this dictionary to a json file i have to have filename in between two inverted commas eg: "sub-310621_task-EMOTION_acq-LR_bold.nii.gz"
SO the output should look like:
intended_for ={"IntendedFor", "sub-310621_task-EMOTION_acq-LR_bold.nii.gz"}
This output will be written in to test.json file which should look like:
{
"IntendedFor": "sub-310621_task-EMOTION_acq-LR_bold.nii.gz"
}
How can i do this in python ?
Upvotes: 9
Views: 24641
Reputation: 128
Rather than trying to build the JSON string yourself you should use the json module to do the encoding.
The json.dumps()
method takes an object such as a dictionary with key value pairs and converts it into a JSON compliant string which can then be written to a file.
Instead of a dictionary, you created a set by using a comma ,
instead of a colon :
intended_for = {"IntendedFor", filename}
The correct code for your input would be
filename = 'sub-310621_task-EMOTION_acq-LR_bold.nii.gz'
intended_for ={"IntendedFor": filename}
Then you can encode
import json
json_string = json.dumps(intended_for)
Upvotes: 7
Reputation: 280207
The apostrophes or quotation marks on the ends of a string literal are not included in the string - 'asdf'
and "asdf"
represent identical strings. Neither the key nor the value in your dict actually include the character '
or "
, so you don't need to perform a conversion.
When you dump the dict to JSON, your JSON dumper will automatically surround strings with "
characters, among other necessary escaping. For example, if you're using the json
module, you can just do
json_string = json.dumps(intended_for)
to produce a correctly-formatted JSON string. (If this does not work, you have some other bug you're not showing us.)
Upvotes: 6