Home > OS >  How to covert a dictionary to a particular form string, with double quotes " replaced by \&quo
How to covert a dictionary to a particular form string, with double quotes " replaced by \&quo

Time:04-09

I have a dictionary like this -

{'type': 2,
 'minutely': {},
 'hourly': {},
 'daily': {'atHour': '17', 'atMinute': '0'},
 'weekly': {'weekdays': []},
 'monthly': {'weekdays': []},
 'advancedCronExpression': ''}

I've done json.dumps to covert this dictionary into a string.

test_string = json.dumps(test_dict)
test_string
O/P: '{"type": 2, "minutely": {}, "hourly": {}, "daily": {"atHour": "17", "atMinute": "0"}, "weekly": {"weekdays": []}, "monthly": {"weekdays": []}, "advancedCronExpression": ""}'

I've to covert it into a target string like this; this is necessary because the api needs it in this form only -

target string -
"{\"type\":2,\"minutely\":{},\"hourly\":{},\"daily\":{\"atHour\":\"17\",\"atMinute\":\"0\"},\"weekly\":{\"weekdays\":[]},\"monthly\":{\"weekdays\":[]},\"advancedCronExpression\":\"\"}"

I've tried like -

test_string.replace('"','\\"')
'{\\"type\\": 2, \\"minutely\\": {}, \\"hourly\\": {}, \\"daily\\": {\\"atHour\\": \\"17\\", \\"atMinute\\": \\"0\\"}, \\"weekly\\": {\\"weekdays\\": []}, \\"monthly\\": {\\"weekdays\\": []}, \\"advancedCronExpression\\": \\"\\"}'

I'm not sure whether I'm approaching this in the right way or not. I've to dynamically update the parameters keeping the same string format. I've tried with Python Regex also. Any suggestion?

CodePudding user response:

    import json

test_dict ={'type': 2,
 'minutely': {},
 'hourly': {},
 'daily': {'atHour': '17', 'atMinute': '0'},
 'weekly': {'weekdays': []},
 'monthly': {'weekdays': []},
 'advancedCronExpression': ''}

test_string = json.dumps(test_dict)
test_string = test_string.replace('"', '\\"')
print(test_string)

with(open('result.txt', "w")) as result:
    result.write(test_string)

for me this returns targeted string results

the thing is that you probably check the test_string value in debugger, where "//" is displayed. Printing the variable on the console, or saving it in file gives you the target string.

CodePudding user response:

inp = {'type': 2,
  'minutely': {},
  'hourly': {},
  'daily': {'atHour': '17', 'atMinute': '0'},
  'weekly': {'weekdays': []},
  'monthly': {'weekdays': []},
  'advancedCronExpression': ''}

target = r'''"{\"type\":2,\"minutely\":{},\"hourly\":{},\"daily\":{\"atHour\":\"17\",\"atMinute\":\"0\"},\"weekly\":{\"weekdays\":[]},\"monthly\":{\"weekdays\":[]},\"advancedCronExpression\":\"\"}"'''

target == json.dumps(json.dumps(inp, separators=(',',':')))
# True

You need to be super careful about how things get printed when you're comparing. This is the difference between __repr__ and __str__. __str__ gets used for print() but just displaying to terminal uses __repr__

Example:

x = """{"a":1}"""
print(x)
# {"a":1}

x
# '{"a":1}'

x2 = json.dumps(x)
print(x2)
# "{\"a\":1}"

x2
# '"{\\"a\\":1}"'
  • Related