【问题标题】:How to convert sql statements to json如何将sql语句转换为json
【发布时间】:2018-06-11 10:59:14
【问题描述】:

我正在寻找this website,它使用插入和创建语句来获取 json 结构。 python中是否有任何相同的方法将具有插入和创建语句的sql查询转换为json格式。

示例: SQL查询:

/**
 * Continents 
 */
SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `continents`
-- ----------------------------
DROP TABLE IF EXISTS `continents`;
CREATE TABLE `continents` (
  `code` char(2) NOT NULL COMMENT 'Continent code',
  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT;

-- ----------------------------
-- Records of continents
-- ----------------------------
INSERT INTO `continents` VALUES ('AF', 'Africa');
INSERT INTO `continents` VALUES ('AN', 'Antarctica');
INSERT INTO `continents` VALUES ('AS', 'Asia');
INSERT INTO `continents` VALUES ('EU', 'Europe');
INSERT INTO `continents` VALUES ('NA', 'North America');
INSERT INTO `continents` VALUES ('OC', 'Oceania');
INSERT INTO `continents` VALUES ('SA', 'South America');
INSERT INTO `continents` VALUES ('??', NULL);

JSON 结构:

{
  "continents": [
    {
      "code": "AF",
      "name": "Africa"
    },
    {
      "code": "AN",
      "name": "Antarctica"
    },
    {
      "code": "AS",
      "name": "Asia"
    },
    {
      "code": "EU",
      "name": "Europe"
    },
    {
      "code": "NA",
      "name": "North America"
    },
    {
      "code": "OC",
      "name": "Oceania"
    },
    {
      "code": "SA",
      "name": "South America"
    },
    {
      "code": "??",
      "name": null
    }
  ]
}

【问题讨论】:

  • 不能从 SQL 中读取数据,然后将读取的数据转换成 JSON 吗?

标签: python sql json


【解决方案1】:

是的,当然有可能——如果有人用一种语言提供了一个可行的实现,那么任何图灵完备的语言都是可能的。

现在您有两种可能的方法来解决这个问题。第一个是编写一个完整的“SQL2json”解析器/标记器/解释器(您可以阅读有关编程语言实现的更多信息),它将解析 SQL 源代码并生成匹配的 json 文本作为结果,或者更多更简单地说,您可以对数据库执行 SQL 源代码,然后使用您的 python DB-API 连接器查询数据库并从查询结果中生成一个字典列表(使用 DictCursor 会变得轻而易举)并使用 json 模块对其进行序列化.

【讨论】:

    猜你喜欢
    • 2021-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-11
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 2011-10-18
    相关资源
    最近更新 更多