简体   繁体   English

JSON的嵌套序列化

[英]Nested serialization for JSON

I'm trying to return a JSON like this after a successful post request. 我试图在成功的发布请求后返回这样的JSON。

{
    "ip": "127.0.0.1",
    "ports": [
        {port: "", service: ""}
    ],
    "first_scan": "date",
    "last_updated": "date"
}

I'm trying to make my serializer so that whenever my nmap function which returns data in this way on the console: 我试图使我的序列化程序,以便每当我的nmap函数以这种方式在控制台上返回数据时:

Host : 127.0.0.1 (localhost) State : up
port : 631      service : CUPS
port : 902      service : VMware Authentication Daemon
port : 6463     service : 
port : 8000     service : WSGIServer/0.2 CPython/3.7.3

It would parse it like the JSON mentioned. 它将像提到的JSON一样进行解析。

I have tried making a model like this in my models.py 我曾尝试在我的models.py制作这样的模型

class nmapScan(models.Model):
    ip = models.CharField(max_length=13, blank=True)
    ports = models.CharField(max_length=5)
    service = models.TextField()
    first_scan = models.DateTimeField(auto_now_add=True)
    last_updated = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['first_scan']

But I'm still confused by this nested serialization concept. 但是我仍然对这个嵌套的序列化概念感到困惑。 How would I go on making the data get parsed from my function, return it like that certain JSON and have it stored in the database (assuming my model is right) properly? 我该如何继续从函数中解析数据,像返回某些JSON一样将其返回并正确地存储在数据库中(假设我的模型正确)?

Depending your DB, you can you use something like this: 根据您的数据库,您可以使用以下内容:

class nmapScan(models.Model):
    ip = models.CharField(max_length=13, blank=True)
    services = JSONField()              # [{"service": "", "port": ""}, ... ]
    first_scan = models.DateTimeField(auto_now_add=True)
    last_updated = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['first_scan']

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

scan = nmapScan.objects.get(...)
for service in scan.services:
    service['port']
    service['name']

Or 要么

class nmapScan(models.Model):
    ip = models.CharField(max_length=13, blank=True)

    first_scan = models.DateTimeField(auto_now_add=True)
    last_updated = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['first_scan']


class Service(models.Model):
    port = models.CharField(max_length=5)
    name = models.TextField()              # service name
    scan = ForeignKey(nmapScan, related_name='services')

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

scan = nmapScan.objects.get(...)
for service in scan.services.all():
    service.port
    service.name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM