使用python读取json文件中的特定属性

2024-04-27 19:27:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写代码,使用python将json模型转换为SQLite。以下是示例json文件:

{  
    "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"
                }
            ]
        }
    }
]

通过下面的代码,我可以读取外键约束。但我很难读懂SQLFK下的“参考”。在

^{pr2}$

请帮助我如何阅读“参考”的内容。在

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

Tags: 代码name模型jsonfieldssqliteprefixtype
2条回答

“reference”指向dict。迭代dict生成dict的键。所以在for reference in constraint["reference"]循环中,reference将首先生成字符串"entityName",然后是字符串"fields"。您显然明白"somestring"["another_string"]没有意义,因为字符串是基于索引的(整数)。在

您缺少一个属性级别(引用)。 怎么样:

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

x将包含{'name':'Code'}

这是非常静态的,这意味着您假设您拥有的json结构与上面几乎相同。在

相关问题 更多 >