Figget
Figget

Reputation: 33

python help me to access json nested and make it looks better

I need help to display a result like result number 2, Below is the full code for result number 1

import json
json_obj = {
"STATUS": "SUCCESS",
"DATA": {
    "data": [
        {
            "destinationId": "216",
            "name": "Bandung",
            "destinationCode": "24417",
            "tourList": []
        },
        {
            "destinationId": "54",
            "name": "Batam",
            "destinationCode": "BTH",
            "tourList": [
                {
                    "tourId": "20586",
                    "tourCode": "IDBTH00585",
                    "tourName": "BATAM SPECIAL SPA PACKAGE",           
                    "tourTime": [
                        {
                            "tourStartTime": "09:00:00",
                            "tourEndTime": "16:00:00",

                        }
                    ],
                    "pricing": [
                        {
                            "adultPrice": "193.00",
                            "tourId": "20586"
                        }
                    ]
                }
            ]
        }          

    ]
 }
}

wanted = ['tourId', 'tourCode', 'tourName', 'tourTime','pricing']

for item in json_obj["DATA"]["data"]:
details = item['tourList']
if not details:
   pass 
else:
   #print(details['tourId'])
  for d in details:
   for key in wanted:
    print(key, ':', json.dumps(d[key], indent=4))

    #Put a blank line at the end of the details for each item
   print()  

Result Number 1 Result

how can i edit the code so the result is like result number 2, just make it become nice to read like result number 2

Result Number 2

tourId : "20586"
tourCode : "IDBTH00585"
tourName : "BATAM SPECIAL SPA PACKAGE"
tourStartTime: "09:00:00"
tourEndTime: "16:00:00"
adultPrice: "193.00"
tourId: "20586"

also 1 more question, can i edit the name of json value into our own string example(tourId : "20586") to (Tour ID : 20586)

Upvotes: 0

Views: 50

Answers (1)

Patrick Artner
Patrick Artner

Reputation: 51663

One way to solve your 2 questions (use 1 only) is to alter your wanted and include a new rewriteDic to replace keys with other values. For parts of wanted that are dict() we handle printing outself. Implicit format for that is a set that takes a list of subkeys, only subkeys will be printed in that case. This is tailored to your given JSON, test with other output before using and adapt accordingly. If we encounter a key that is given inside rewriteDic we use the value there for printing instead of the "real" key:

Code is commented to explain what's being done:

wanted = ['tourId', 'tourCode', 'tourName', 
          {'tourTime':['tourStartTime','tourEndTime']}, # if we encounter a dict we change
          {'pricing':['adultPrice','tourId']}           # the printing mechanics
         ]

rewriteDic = {'tourId':'Tour ID', 'tourCode':'Super Douper Cool and Secret ID Code'}

for item in json_obj["DATA"]["data"]:
    details = item['tourList']
    if not details:
        pass 
    else:
        #print(details['tourId'])
        for d in details:
            for key in wanted:
                if isinstance(key, dict): # got a dict, so our "wanted" contains the real
                    for sub in key:       # subkeys as list as value inside the dict
                        subKeys = key[sub]       # this is what we want to print 
                        for sKey in subKeys:     # so for all that are in 
                            # ask rewriteDic for the value of sKey, else use sKey
                            print( rewriteDic.get(sKey,sKey),":",d[sub][0][sKey])

                else:
                    # Edit: apply rewriteDic here too: 
                    # print(key, ':', json.dumps(d[key], indent=4))
                print(rewriteDic.get(key,key),':',d[key])

        # Put a blank line at the end of the details for each item
        print()  

Output:

Tour ID : 20586
Super Douper Cool and Secret ID Code : IDBTH00585
tourName : BATAM SPECIAL SPA PACKAGE
tourStartTime : 09:00:00
tourEndTime : 16:00:00
adultPrice : 193.00
Tour ID : 20586

Upvotes: 1

Related Questions