0

How to parse python json object?

Currently i'm getting this value from another json file, it is a variable "Id6087b9b5b5" But what if i don't know the object string but i want to fetch "_number" in a loop?

try.py

for sub_dict in y[ChangeID]:  #ChangeID is a variable
    print (ChangeID)
    MERGENUM = (entry['_number'])
    print (MERGENUM

)

data.json

  {
      "Id6087b9b5b5": [
        {
          "status": "NEW",
          "_number": 35328
        }
      ],
      "Id6087b9b345": [
        {
          "status": "NEW",
          "_number": 35348
        }
      ],
      "Id6087b9b555": [
        {
          "status": "NEW",
          "_number": 35310
        }
      ],
      "Id6087b9b5b4": [
        {
          "status": "NEW",
          "_number": 35308
        }
      ]
    }

output as a variable

35328
35348
35310
35308
5
  • What is entry? Commented Aug 31, 2018 at 16:20
  • I'm trying to fetch data of "_number" Commented Aug 31, 2018 at 16:23
  • I understand that, but entry is not defined in your code. Commented Aug 31, 2018 at 16:24
  • should entry - > sub_dict? if not then something is missing from your post Commented Aug 31, 2018 at 16:24
  • yeah, that is correct... replacing entry with sub_dict works.. i made a mistake.. But what if i don't know the object string "Id6087b9b5b4", how can i still get the desired output? Commented Aug 31, 2018 at 16:28

1 Answer 1

2

You can use json parse the json string to object and then iterate the object with for loop (in this way, you don't need to know the IDs) and get the inner object, each inner object is an array which use inner_object[0] to get the first object:

import json
data = '''{
      "Id6087b9b5b5": [
        {
          "status": "NEW",
          "_number": 35328
        }
      ],
      "Id6087b9b345": [
        {
          "status": "NEW",
          "_number": 35348
        }
      ],
      "Id6087b9b555": [
        {
          "status": "NEW",
          "_number": 35310
        }
      ],
      "Id6087b9b5b4": [
        {
          "status": "NEW",
          "_number": 35308
        }
      ]
    }'''

print(data)

obj = json.loads(data)

for nid in obj:
    inner_obj = obj[nid][0]
    num = inner_obj['_number']
    print(num)
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you this is what i was looking for.. same logic can be applied if the data is a text file, correct?
@Mihir no, not unless that text file happened to contain a valid json object
By text file, i meant data.json file.
@Mihir then you would want to open the file and use json.load() (note the lack of s at the end, which signifies "string")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.