konstantin
konstantin

Reputation: 893

Update correctly the fields of the json file for REST API

I am retrieving a json file with REST API using a GET in python and want to retrieve the json file update some values of it and then update that value. My get is the following:

 r1 = requests.get(url)

It returns the whole json file. Now I want to update some values of the json and put it back using PUT REST API call. My put command is the following:

requests.put(url, json=r1)

The fields I want to update are the following:

r1.json()['a']['a'] = 2 // print r1.json()['a']['a'] ->1
r1.json()['a']['b'] = 2 // print r1.json()['a']['b'] ->1
r1.json()['a']['c'] = 2 // print r1.json()['a']['c'] ->1

My question is how can I update correctly the fields of my json?

Upvotes: 0

Views: 2053

Answers (2)

bruno desthuilliers
bruno desthuilliers

Reputation: 77912

To improve on bluesummer's answer, response.json() is merely a shortcut for json.loads(response.content), and it creates a new dict each time it's called. IOW what this code:

r1.json()['a']['a'] = 2

is

  • create a dict from r1.content
  • update this dict
  • and finally discard it.

which is why you have to keep a reference to the dict (assign it to a variable) if you want to update it.

Upvotes: 1

bluesummers
bluesummers

Reputation: 12637

You should save it as a variable, modify it and then send it back

my_json = r1.json()
my_json['a']['a'] = 2
my_json['a']['b'] = 2
my_json['a']['c'] = 2
requests.put(url, json=my_json)

What you are doing in your code essentialy, is calling .json() which generates a dictionary from the response, you are not really modifying the response object - but really modifying the result of the returned value from the .json() call.

Upvotes: 1

Related Questions