简体   繁体   中英

Read the specific attribute in the json file using python

I'm writing code to convert a json model to SQLite using python. Here is the sample json file:

{  
    "type":"MetaModel",
    "entityName":{  
    "prefix":"Rail",
    "name":"LocationProvider"
},
"attributes":[  
    {  
        "name":"abc",
        "type":"string",
        "maxLength":10,
        "mandatory":true
    }
],
"constraints":[
    {
        "name": "PrimaryKey",
        "type": "SQLPK",
        "fields": [
            {  
                "name":"abc"
            }
        ]
    },
    {
        "name": "ForeignKeyOne",
        "type": "SQLFK",
        "fields": [
            { 
                "name":"ab"
            }
        ],
        "reference":{
            "entityName":{
                "prefix":"Rail",
                "name":"ProvinceState"
            },
            "fields":[
                {
                    "name":"Code"
                }
            ]
        }
    }
]

with the below code I'm able to read the foreign key constraints. But I'm struggling to read the "reference" under the SQLFK.

if constraint["name"] ==  "ForeignKeyOne":
    for field in constraint["fields"]:
       fk_attribute_list.append(field["name"])

Please help me on how to read the content "reference".

"reference":{
    "entityName":{
        "prefix":"Rail",
        "name":"ProvinceState"
     },
     "fields":[
          {
              "name":"Code"
          }
     ]
 }

You're missing a level of attribute (reference). How about:

if constraint["name"] ==  "ForeignKeyOne":
    for field in constraint["reference"]:
        if field == 'fields':
            for x in constraint["reference"][field]:
                print x

x would contain {'name':'Code'}

That's pretty static, meaning you assume the json structure you have is pretty much the same as above.

The "reference" points to a dict. Iterating over a dict yields dict's keys. So in your for reference in constraint["reference"] loop, reference will first yield the string "entityName" then the string "fields" . You obviously understand that "somestring"["another_string"] makes no sense, since strings are index-based (integers).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM