I am writing a python code to scrape website data through cURL. I converted cURL into python code using https://curlconverter.com/ . The code works just fine but I want to customize according to my need like in this line of code
data = '{"appDate":{"startDate":"2022-01-05T18:30:00.000Z","endDate":"2022-01-06T18:30:00.000Z"},"page_number":1,"page_size":20,"sort":{"key":"AppointmentStartTime","order":-1}}'
After "startDate" I want to add my variable (startdate) which I created like this
I tried to add variables like this
data = '{"appDate":{"startDate":' startdate ,"endDate":' enddate '},"page_number":1,"page_size":20,"sort":{"key":"AppointmentStartTime","order":-1}}' but this did not work.
Also adding ' str(startdate) ' did not help.
Please can anyone tell me how this should be done.
CodePudding user response:
You might want to transform the json data string into a dictionary using the json module. Then you can freely manipulate and export your data.
import json
raw_data = '{"appDate":{"startDate":"2022-01-05T18:30:00.000Z","endDate":"2022-01-06T18:30:00.000Z"},"page_number":1,"page_size":20,"sort":{"key":"AppointmentStartTime","order":-1}}'
data = json.loads(raw_data) # load json from string to dict
data['appDate']['startDate'] = 23
data['appDate']['endDate'] = 42
print(json.dumps(data)) # export dict to json string
CodePudding user response:
In the example you have shown, there is probably only a small mistake right after startdate , with the apostrophe. Compare carefully:
Your code (with the mistake):
data = '{"appDate":{"startDate":' startdate ,"endDate":' enddate '},"page_number":1,"page_size":20,"sort":{"key":"AppointmentStartTime","order":-1}}'
^
SyntaxError: invalid syntax
Fixed code:
data = '{"appDate":{"startDate":' startdate ',"endDate":' enddate '},"page_number":1,"page_size":20,"sort":{"key":"AppointmentStartTime","order":-1}}'
