-2

I have the following string of data:

{"responseStatus":"ok","responseHeader":{"now":1528734419187,"status":"ok","requestId":"Wx6i0wquZS4AAFNeStwAAABg"},"responseData":{"id":38}}

and I need to pull the "id":38 out of it and format it a "id":"38"

Xantium
  • 11,201
  • 10
  • 62
  • 89
David S.
  • 13
  • 1
  • 2
    This isn't a string at all, it's a `dict`, but if not you should probably just use `json.loads` on it and treat it like a normal `dict` – Ofer Sadan Jun 12 '18 at 20:07
  • 2
    You have a dictionary, not a string pf data. So, just use dictionary indexing. – DYZ Jun 12 '18 at 20:07
  • Possible duplicate of [Rearranging levels of a nested dictionary in python](https://stackoverflow.com/questions/33425871/rearranging-levels-of-a-nested-dictionary-in-python) – David C. Jun 13 '18 at 00:12

2 Answers2

2

since you're using the requests library (based on your tag), when calling your repsonse, instead of returning .content, you can return .json():

response = requests.get(....).json()
response['responseData']['id'] = str(response['responseData']['id'])   # or you can just do "38"
crookedleaf
  • 2,118
  • 4
  • 16
  • 38
0

You could use the json module:

import json
json_s = json.loads('{"responseStatus":"ok","responseHeader":{"now":1528734419187,"status":"ok","requestId":"Wx6i0wquZS4AAFNeStwAAABg"},"responseData":{"id":38}}')

json_s['responseData']['id'] = '38' # Or str(json_s['responseData']['id'])


print(json_s)

Or in this case it is a valid dictionary so you could use eval():

json_s = '{"responseStatus":"ok","responseHeader":{"now":1528734419187,"status":"ok","requestId":"Wx6i0wquZS4AAFNeStwAAABg"},"responseData":{"id":38}}'

a = eval(json_s)

a['responseData']['id'] = '38' # Or str(a['responseData']['id'])

print(a)

If you want to convert the dictionary in json_s and a back to a string then just use str(json_s) and str(a) respectively.

See the documentation for the use of eval().

Otherwise to keep away from eval() use the ast module. As described here:

Convert a String representation of a Dictionary to a dictionary?

Xantium
  • 11,201
  • 10
  • 62
  • 89
  • 1
    `eval()` is evil and really shouldn't be used unless absolutely necessary. also, their question is how to change the value of a key, but there's no mention of how to do so in your answer. – crookedleaf Jun 12 '18 at 20:15
  • @crookedleaf Thank you. I've fixed my answer. – Xantium Jun 12 '18 at 20:22