0

I have a variable group_array like this

groups_array=[{"group": "18652_PDR"}, {"group": "11262_PDR"}, {"group": "3787_PDR"}, {"group": "4204_PDR"}]

I want to put the groups_array variable inside below string so I tried like this using the f method

data = f'{"request":{"streaming_type":"quote", "data":{"groups": {groups_array}}, "request_type":"subscribe", "response_format":"json"}}'

But am getting error deeply nested error

I want the string to be in below format after adding the variable

data = '{"request":{"streaming_type":"quote", "data":{"groups": [{"group": "18652_PDR"}, {"group": "11262_PDR"}, {"group": "3787_PDR"}, {"group": "4204_PDR"}]}, "request_type":"subscribe", "response_format":"json"}}'

Could someone tell me how can I properly do it in this case as there are too many "" and {}?

2
  • 1
    Are you trying to create json? Commented May 26, 2021 at 13:27
  • @PatrickArtner trying to send the data to an api using websocket. This is the format it is expecting Commented May 26, 2021 at 13:32

2 Answers 2

2

You can just use the built-in json package. You would create a dictionary of your data and pass it to json.dumps to receive the json string.

import json
groups_array = [{"group": "18652_PDR"}, {"group": "11262_PDR"}, {"group": "3787_PDR"}, {"group": "4204_PDR"}]
data = {"request":
            {"streaming_type": "quote",
             "data": {
                     "groups": groups_array
             },
             "request_type": "subscribe",
             "response_format": "json"
             }
        }

data_json = json.dumps(data)
print(data)

# Output:
{'request': {'streaming_type': 'quote', 'data': {'groups': [{'group': '18652_PDR'}, {'group': '11262_PDR'}, {'group': '3787_PDR'}, {'group': '4204_PDR'}]}, 'request_type': 'subscribe', 'response_format': 'json'}}
Sign up to request clarification or add additional context in comments.

Comments

1

You can assign directly to dict and create a json (stringify it) if your request needs string:

import json

data = json.dumps({"request":{"streaming_type":"quote", "data":{"groups": groups_array}, "request_type":"subscribe", "response_format":"json"}})

Or if dictionary is also an option - pass it without json.dumps

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.