0

How can I get the parent of the element in JSON? For example, In the JSON below,

When I use print(json["phones"]), the result I want to happpen is:

[iphone1, iphone2] 

but instead, I am getting this:

{'iphone1': {'test': ''}, 'iphone2': {'test': ''}}

Sorry I am new on python and JSON, the sample code is below. Thank you!

{
  "phones":
  {
    "iphone1":
    {
      "test": ""
    },

    "iphone2":
    {
      "test": ""
    }
  }
}
martineau
  • 119,623
  • 25
  • 170
  • 301
Ppap
  • 67
  • 7
  • 1
    You definitely want to convert your json into a dictionary as a dict will let you manipulate things better. Also, once it's a dictionary you will gain access to the `.keys()` function that will do exactly what you are asking for. – Rashid 'Lee' Ibrahim May 08 '22 at 15:18

1 Answers1

2

When I print(json["phones"]), the result I want to happpen is:

[iphone1, iphone2] 

What do you mean by iphone1? You mean "iphone1"?


What you want are the keys of the JSON object (equivalent to Python dict), so you can use the dict().keys() method, which returns a list with the keys of the dictionary.

>>> print(json["phones"])
{'iphone1': {'test': ''}, 'iphone2': {'test': ''}}
>>> print(json["phones"].keys())
['iphone1', 'iphone2']
FLAK-ZOSO
  • 3,873
  • 4
  • 8
  • 28
  • I see I'm getting a couple of upvotes, thank you for this +10s. If among the upvoters there was the OP @Ppap please let me know that, if the solution didn't work feel free to ask, otherwise accept the answer. – FLAK-ZOSO May 08 '22 at 15:35