Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Problem with Json Array
#1
I have a problem with modifying an array of JSON message.
I created array a and array using 2 different method.
Then I tried to change one of the key value "arrayA" of the first element in both array
While array a gives me the desired result, array b does not.
All the key value "arrayA" in array b has been.

a = [{"arrayA":1, "arrayB":6},{"arrayA":1, "arrayB":6},{"arrayA":1, "arrayB":6}]
a[0]["arrayA"] = 4
print(a)

b = [{"arrayA":1, "arrayB":6}] * 3
b[0]["arrayA"] = 4
print(b)

=============== RESTART: C:/Users/HomeAdmin/Desktop/jsonarray.py ===============
[{'arrayA': 4, 'arrayB': 6}, {'arrayA': 1, 'arrayB': 6}, {'arrayA': 1, 'arrayB': 6}]
[{'arrayA': 4, 'arrayB': 6}, {'arrayA': 4, 'arrayB': 6}, {'arrayA': 4, 'arrayB': 6}]
>>>

Can anyone tell me what is wrong?

TIA
kwekey
Reply
#2
This does not give you three dictionaries. It gives you 1 dictionary three times.
b = [{"arrayA":1, "arrayB":6}] * 3
Essentially what you are doing is this:
a = {"arrayA":1, "arrayB":6}
b = [a, a, a]
You could use a comprehension.
b = [{"arrayA":1, "arrayB":6} for _ in range(3)] 
This is not a json thing. It is a characteristic of lists and a very common and confusing Python problem
Reply
#3
Thanks Dean,

That's sounds logical.
I recode accordingly and try again.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Problem with nested JSON Kalet 7 2,719 Dec-09-2021, 11:13 PM
Last Post: Gribouillis
  Problem to parse a json enigma619 3 2,342 Dec-04-2020, 08:16 AM
Last Post: enigma619
  Array problem in pylab module - Image processing bobfat 0 1,684 Dec-31-2019, 06:02 PM
Last Post: bobfat
  json problem enigma619 9 3,614 Dec-19-2019, 08:29 AM
Last Post: enigma619
  Output to a json file problem Netcode 3 3,663 Nov-22-2019, 01:44 AM
Last Post: Skaperen
  convert a json file to a python dictionnary of array Reims 2 2,205 Sep-10-2019, 01:08 PM
Last Post: Reims
  Python convert csv to json with nested array without pandas terrydidi 2 9,566 Jan-12-2019, 02:25 AM
Last Post: terrydidi
  Array - Problem with Simple Code emerger 8 4,341 Oct-12-2018, 02:46 AM
Last Post: ichabod801
  Array/Jarray problem contains null value? Maverick0013 1 3,933 Aug-10-2018, 12:56 PM
Last Post: Windspar
  json load problem mepyyeti 6 4,813 Dec-28-2017, 02:15 AM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020