在python中将数据库转换为具有特定格式的json

时间:2018-01-11 10:15:38

标签: python json

我是python中的初学者。我试图读取我的数据库并使用以下格式写入json文件

{"intents": [
    {"tag": "greeting",
     "patterns": ["hello"],
     "responses": ["hello"]
    },
    {"tag": "greeting",
     "patterns": ["are you fine"],
     "responses": ["yeah"]
    }
   ]
}

我关注数据库

tag         patterns        responses
greeting    hello           hello
greeting    are you fine    yeah

我已尝试过此代码:

connection = sqlite3.connect('database.db')
c = connection.cursor()


def writeToJSONFile(path, fileName, data):
    filePathNameWExt = './' + path + '/' + fileName + '.json'
    with open(filePathNameWExt, 'w') as fp:
        json.dump(data, fp)

result = c.execute("SELECT * FROM reply").fetchall()

data = {}
data['intents'] = [{***some code here***}]

writeToJSONFile('./','intents',data)

我无法为json部分编写代码。欢迎任何帮助,建议

1 个答案:

答案 0 :(得分:1)

假设结果如下:

>>>print(result)
[['greeting','hello','hello'],['greeting','are you fine','yeah']]

以下行将按照您希望的方式在dict中生成数据:

data = { 'intents': [ 
              {'tag':row[0],
               'patterns':[row[1]],
               'responses':[row[2]]
              }
              for row in result]
       }

注意:我尝试使格式化更容易阅读,这里是oneline

data = { 'intents': [ {'tag':row[0], 'patterns':[row[1]], 'responses':[row[2]]} for row in result]  }

您可以打印数据以帮助验证其是否正确:

>>> import json
>>> print(json.dumps(data, indent=4, sort_keys=True))
{
"intents": [
    {
        "patterns": [
            "hello"
        ],
        "responses": [
            "hello"
        ],
        "tag": "greeting"
    },
    {
        "patterns": [
            "are you fine"
        ],
        "responses": [
            "yeah"
        ],
        "tag": "greeting"
    }
  ]
}