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 ?
Generally, double quotes are used for string representation and single quotes are used for regular expressions, dict keys or SQL. Hence both single quote and double quotes depict string in python but it's sometimes our need to use one type over the other.
Use the str. replace() method to replace single with double quotes in each string.
In a string enclosed in double quotes " , single quotes ' can be used as is, but double quotes " must be escaped with a backslash and written as \" .
Use the json. dumps() method to convert a dictionary to a string with double quotes, e.g. json_str = json. dumps(my_dict) .
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)
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With