2

I have a variable that looks like this:

data = {"add_content": {"errata_ids": [advisory]},"content_view_version_environments": [{"content_view_version_id": version_id}]}

I need to add single quotes to this variable , i.e. if I will assign the variables:

advisory and version_id and add the single quotes to data variable like this:

data = '{"add_content": {"errata_ids": ["RHSA-2017:1390"]},"content_view_version_environments": [{"content_view_version_id": 160}]}'

I am able to post to the API

I have tried to add the single quotes in variety of ways:

new_data = "'" + str(data) + "'"
>>> new_data
'\'{\'add_content\': {\'errata_ids\': [\'"RHSA-2017:1390"\']}, \'content_view_version_environments\': [{\'content_view_version_id\': \'160\'}]}\'' 

or using:

'"%s"'%(data)

and a few more ways.

How can I add the single quotes to the outer to the data variable before and after the opening { and closing }?

Tonechas
  • 13,398
  • 16
  • 46
  • 80
Max_il
  • 151
  • 2
  • 9
  • 2
    What you're trying to create is JSON, so use the `json` module. – Barmar Jul 12 '17 at 17:12
  • 1
    Python's string representation of a `dict` instance isn't necessarily valid JSON. – chepner Jul 12 '17 at 17:14
  • Possible duplicate of [Python dump dict to json file](https://stackoverflow.com/questions/17043860/python-dump-dict-to-json-file) – zwer Jul 12 '17 at 17:16

2 Answers2

3

This is exactly what JSON does:

import json
new_data = json.dumps(data)
Lgiro
  • 762
  • 5
  • 13
1

If in contrary of previous answers and comments you are not trying to convert to a json string then use string.format around the variables:

data = {"add_content": {"errata_ids": '[{}]'.format(advisory)},"content_view_version_environments": [{"content_view_version_id": '{}'.format(version_id)}]}
lee-pai-long
  • 2,147
  • 17
  • 18