简体   繁体   中英

JSON value key pair to contain double quote using Python

I am trying to fetch the json key values using python.

Initially i have my json value in a string variable and later i am converting into dictionary value,

data='{"enc_column": "5", "Delimiter": ";"}'
pair=json.loads(data)
print (pair['Delimiter'])

Result- ; (semi-colon)

But in my case the delimiter i expect is ";" (semicolon enclosed within double quotes) So i tried the below,

data='{"enc_column": "5", "Delimiter": '";"'}'
pair=json.loads(data)

But getting the below error, 在此处输入图片说明

Can anyone suggest to get the result of delimiter as ";" instead of just ; using Python

I am not expecting to join the double quotes after the semicolon is alone returned.

You need to escape the backslash in the json and single quotes aren't allowed in json :

import json
data='{"enc_column": "5", "Delimiter": "\\";\\""}'
pair=json.loads(data)
print (pair['Delimiter'])

PS: Normally you would not write your json manually but it would be printed by some other component, like another python script for example. In that case escaping the double quote would be done by the json serializer:

import json
data = {'delimiter': '";"'}
print(json.dumps(data))

Output:

{"delimiter": "\";\""}

If you take this string and put it into a python script:

string = '{"delimiter": "\";\""}'
print(string)

Output:

{"delimiter": "";""}

you'll see that you have to escape the \\ to prevent it from get interpreted (and thereby consumed) by Python:

string = '{"delimiter": "\\";\\""}'
print(string)

Output (as needed):

{"delimiter": "\";\""}

You need to use double back-slash \\\\ to escape double-quotes " in JSON:

An escaped version of your JSON evaluated in JS is in below snippet. Returned value is ";"

 data='{"enc_column": "5", "Delimiter": "\\\\";\\\\""}' pair=JSON.parse(data) console.log((pair['Delimiter']))

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