如何将JSON数据转换为MySQL INSERT和CREATE TABLE查询?

问题描述 投票:0回答:2

我有一个 JSON 数据集,其中包含我想要插入到 MySQL 数据库中的锻炼信息。

每个练习都有名称、力量、级别等属性

我需要将此 JSON 数据转换为 MySQL INSERT 语句以将数据添加到表中,以及 CREATE TABLE 语句来定义表结构。

以下是 JSON 数据的示例片段:

"exercises": [
    {
      "name": "3/4 Sit-Up",
      "force": "pull",
      "level": "beginner",
      "mechanic": "compound",
      "equipment": "body only",
      "primaryMuscles": [
        "abdominals"
      ],
      "secondaryMuscles": [],
      "instructions": [
        "Lie down on the floor and secure your feet. Your legs should be bent at the knees.",
        "Place your hands behind or to the side of your head. You will begin with your back on the ground. This will be your starting position.",
        "Flex your hips and spine to raise your torso toward your knees.",
        "At the top of the contraction your torso should be perpendicular to the ground. Reverse the motion, going only ¾ of the way down.",
        "Repeat for the recommended amount of repetitions."
      ],
      "category": "strength"
    },
    {
      "name": "90/90 Hamstring",
      "force": "push",
      "level": "beginner",
      "mechanic": null,
      "equipment": "body only",
      "primaryMuscles": [
        "hamstrings"
      ],
      "secondaryMuscles": [
        "calves"
      ],
      "instructions": [
        "Lie on your back, with one leg extended straight out.",
        "With the other leg, bend the hip and knee to 90 degrees. You may brace your leg with your hands if necessary. This will be your starting position.",
        "Extend your leg straight into the air, pausing briefly at the top. Return the leg to the starting position.",
        "Repeat for 10-20 repetitions, and then switch to the other leg."
      ],
      "category": "stretching"
    },
    {
      "name": "Ab Crunch Machine",
      "force": "pull",
      "level": "intermediate",
      "mechanic": "isolation",
      "equipment": "machine",
      "primaryMuscles": [
        "abdominals"
      ],
      "secondaryMuscles": [],
      "instructions": [
        "Select a light resistance and sit down on the ab machine placing your feet under the pads provided and grabbing the top handles. Your arms should be bent at a 90 degree angle as you rest the triceps on the pads provided. This will be your starting position.",
        "At the same time, begin to lift the legs up as you crunch your upper torso. Breathe out as you perform this movement. Tip: Be sure to use a slow and controlled motion. Concentrate on using your abs to move the weight while relaxing your legs and feet.",
        "After a second pause, slowly return to the starting position as you breathe in.",
        "Repeat the movement for the prescribed amount of repetitions."
      ],
      "category": "strength"
    }]

任何人都可以提供有关如何编写脚本或 SQL 查询以有效实现此转换的指导吗?

谢谢!

mysql json type-conversion
2个回答
0
投票

要使用 SQL 而不是 Python 来实现转换,您可以直接在 SQL 中创建表并生成 INSERT 语句。

-- Create table to store exercise data
CREATE TABLE IF NOT EXISTS exercises (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    force VARCHAR(255),
    level VARCHAR(255),
    mechanic VARCHAR(255),
    equipment VARCHAR(255),
    primaryMuscles VARCHAR(255),
    secondaryMuscles VARCHAR(255),
    instructions TEXT,
    category VARCHAR(255)
);

-- Insert statements for each exercise
INSERT INTO exercises (name, force, level, mechanic, equipment, primaryMuscles, secondaryMuscles, instructions, category)
VALUES 
(
    '3/4 Sit-Up',
    'pull',
    'beginner',
    'compound',
    'body only',
    'abdominals',
    NULL,
    'Lie down on the floor and secure your feet. Your legs should be bent at the knees.\nPlace your hands behind or to the side of your head. You will begin with your back on the ground. This will be your starting position.\nFlex your hips and spine to raise your torso toward your knees.\nAt the top of the contraction your torso should be perpendicular to the ground. Reverse the motion, going only ¾ of the way down.\nRepeat for the recommended amount of repetitions.',
    'strength'
),
(
    '90/90 Hamstring',
    'push',
    'beginner',
    NULL,
    'body only',
    'hamstrings',
    'calves',
    'Lie on your back, with one leg extended straight out.\nWith the other leg, bend the hip and knee to 90 degrees. You may brace your leg with your hands if necessary. This will be your starting position.\nExtend your leg straight into the air, pausing briefly at the top. Return the leg to the starting position.\nRepeat for 10-20 repetitions, and then switch to the other leg.',
    'stretching'
);

在此 SQL 脚本中:

CREATE TABLE 语句创建一个名为练习的表,其中的列与练习的属性相对应。 INSERT INTO 语句将每个练习的数据插入到练习表中。 您可以在 MySQL 数据库中执行此 SQL 脚本来创建表并插入数据。根据您的特定 JSON 数据的需要调整 INSERT INTO 语句中的数据。


0
投票

伙计们,这是我如何使用 python 脚本解决问题的。 首先创建适合您的 json 数据的数据库和表。

CREATE TABLE exercises (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255),
    force_type VARCHAR(50),
    level VARCHAR(50),
    mechanic VARCHAR(50),
    equipment VARCHAR(50),
    primary_muscles JSON,
    secondary_muscles JSON,
    instructions JSON,
    category VARCHAR(50)
);
import mysql.connector
import json

# MySQL bağlantısını kur
mydb = mysql.connector.connect(
  host="localhost",
  user="yourname",
  password="yourpass",
  database="your db"
)
cursor = mydb.cursor()

# JSON dosyasını oku
with open('exercises.json') as f:
    print("Dosya okundu")
    data = json.load(f)
    ##print type of data
    


# Verileri MySQL'e ekle
for exercise in data:
    print("Veri ekleniyor: " + exercise['name'])
    sql = "INSERT INTO exercises (name, force_type, level, mechanic, equipment, primary_muscles, secondary_muscles, instructions, category) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)"
    print(exercise['primaryMuscles'])
    val = (
        exercise['name'],
        exercise['force'],
        exercise['level'],
        exercise['mechanic'],
        exercise['equipment'],
        json.dumps(exercise['primaryMuscles']),
        json.dumps(exercise['secondaryMuscles']),
        json.dumps(exercise['instructions']),
        exercise['category'],
    )
    cursor.execute(sql, val)

# Değişiklikleri kaydet
mydb.commit()

# Bağlantıyı kapat
mydb.close()
© www.soinside.com 2019 - 2024. All rights reserved.