如何将json序列化为sql?

Posted

技术标签:

【中文标题】如何将json序列化为sql?【英文标题】:How to serialize json to sql? 【发布时间】:2022-01-18 05:54:41 【问题描述】:

我有一个单词列表,我应该向 API 发送请求并获取有关单词的信息。我想在 Django 中将 JSON 格式的 API 数据转换为 SQL(我的数据库是 PostgreSQL)格式。我怎样才能做到这一点?你知道任何学习将 json 序列化为 sql 的好资源吗? 我刚开始学习 Django。

是 API 的 JSON 数据:

  [
    
      "word": "hello",
      "phonetics": [
        
          "text": "/həˈloʊ/",
          "audio": "https://lex-audio.useremarkable.com/mp3/hello_us_1_rr.mp3"
        ,
        
          "text": "/hɛˈloʊ/",
          "audio": "https://lex-audio.useremarkable.com/mp3/hello_us_2_rr.mp3"
        
      ],
      "meanings": [
        
          "partOfSpeech": "exclamation",
          "definitions": [
            
              "definition": "Used as a greeting or to begin a phone conversation.",
              "example": "hello there, Katie!"
            
          ]
        ,
        
          "partOfSpeech": "noun",
          "definitions": [
            
              "definition": "An utterance of “hello”; a greeting.",
              "example": "she was getting polite nods and hellos from people",
              "synonyms": [
                "greeting",
                "welcome",
                "salutation",
                "saluting",
                "hailing",
                "address",
                "hello",
                "hallo"
              ]
            
          ]
        ,
        
          "partOfSpeech": "intransitive verb",
          "definitions": [
            
              "definition": "Say or shout “hello”; greet someone.",
              "example": "I pressed the phone button and helloed"
            
          ]
        
      ]
    
  ]

这是我的models.py:

class Words(models.Model):
    word = models.CharField(max_length=50)
    american_phonetic= models.CharField(max_length=50)
    american_audio=  models.URLField(max_length = 200)
    british_phonetic= models.CharField(max_length=50)
    british_audio=  models.URLField(max_length = 200)

###########################################################################

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    birth_date = models.DateField('birth date')
    field= models.CharField(max_length=50)
    location = models.CharField(max_length=30, blank=True)
    interest= models.IntegerField() # for example :  1 for science , 2 for art , 3 for sport etc.
    education= models.IntegerField() # for example : 1 for highschool , 2 for bachelor , 3 for master and 4 for phd

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()

class UserLearned(models.Model):
    Profile_id = models.ForeignKey(Profile, on_delete=models.CASCADE)
    word_id = models.ForeignKey(Words, models.SET_NULL, blank=True, null=True,)

    def __str__(self):
        return self.word_id


############################################################################

class Meanings(models.Model):
    word_id = models.ForeignKey(Words, on_delete=models.CASCADE)
    partOfSpeech = models.CharField(max_length=30)

class Definitions(models.Model):
    word_id = models.ForeignKey(Words, on_delete=models.CASCADE)
    Meaning_id = models.OneToOneField(Meanings, on_delete=models.CASCADE, primary_key=True)
    definition = models.TextField()

    def __str__(self):
        return self.definition


class Examples(models.Model):
    word_id = models.ForeignKey(Words, on_delete=models.CASCADE)
    Meaning_id = models.OneToOneField(Meanings, on_delete=models.CASCADE, primary_key=True)
    example = models.TextField()

    def __str__(self):
        return self.example

class Synonyms(models.Model):
    word_id = models.ForeignKey(Words, on_delete=models.CASCADE)
    Meaning_id = models.ForeignKey(Meanings, on_delete=models.CASCADE)
    synonym = models.CharField(max_length=50)

    def __str__(self):
        return self.synonym

【问题讨论】:

【参考方案1】:

您可以使用 json 库来序列化 json 数据,反之亦然(使用 json.loads()json.dumps() 方法)。

例如:

import json

data = "'name': 'Jack', 'age': 30"     #json data
python_dict = json.loads(data)           #now it is a python dict

现在您可以直接将 python dict 的值分配给 Django 中的任何模型属性。

以下是一些开始学习库的好资源:

https://www.w3schools.com/python/python_json.asp https://docs.python.org/3/library/json.html

【讨论】:

以上是关于如何将json序列化为sql?的主要内容,如果未能解决你的问题,请参考以下文章

如何用C#将序列化为json的字符串导入到sql server中数据库

如何在C#中将Linq to SQL数据序列化为JSON

如何将 SqlAlchemy 结果序列化为 JSON?

如何将属性序列化为 json 对象?

如何将java对象序列化/反序列化为javax.JSON

将小数序列化为 JSON,如何四舍五入?