无法在DynamicEmbeddedDocument中保存复杂的JSON结构(Mongoengine,Flask)

时间:2017-10-12 02:02:57

标签: python json mongodb flask mongoengine

尝试使用mongoengine将JSON请求保存到MongoDB中的DynamicDocument时遇到问题。

这是我的文件:

class documentSource(DynamicEmbeddedDocument):
    name = StringField()

class documentParent(Document):
    name = StringField(max_length=120)
    source = ListField(EmbeddedDocumentField('documentSource'))

这是我的请求POST对象:

{
      "name": "Test", 
      "source": [{
          "name": "my first source"
          "metadata": {
            "name": "testing",
            "products": [
                {"name":"my product", "price":123}
            ]
          }
       },{
          "name": "my second source"
          "metadata": {
            "name": "Test",
            "profile": "foo"
          }
       }
      ]
    }

这是我的Flask post方法:

def post(self):
        myObj = documentParent(
            name=self.data['name'],
            description=self.data['description'],
        )

        sourceList = []
        for i in self.data['source']:
            content = documentSource(**i)
            sourceList.append(content)
        myObj.source = sourceList
        myObj.save()

但问题是:

如果我发送此JSON不起作用:

{
      "name": "Test", 
      "source": [{
          "name": "my first source"
          "metadata": {
            "name": "testing",
            "products": [
                {"name":"my product", "price":123}
            ]
          }
       },{
          "name": "my second source"
          "metadata": {
            "name": "Test",
            "profile": "foo",
            "foo" : {
              "foo1": "var1"
            }
          }
       }
      ]
    }

但是这个对象有效:

{
      "name": "Test", 
      "source": [{
          "name": "my first source"
          "metadata": {
            "name": "testing",
            "products": [
                "my product"
            ]
          }
       },{
          "name": "my second source"
          "metadata": {
            "name": "Test",
            "profile": "foo"
          }
       }
      ]
    }

列表清单存在同样的问题:

"image":
  {"available_sizes":
    [[[150,
       19],
      "assets/images/150x150.png"],
     [[250,
       31],
      "assets/images/250x250.png"],
     [[450,
       57],
      "assets/images/450x450.png"]]

我认为使用复杂的json'结构mongoengine的解析器不起作用。我不知道如何找出这个问题,因为我无法控制源信息,大图是从源(例如:网站爬虫)获取JSON对象并将其保存(如果它来)到我的DynamicDocument中。

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您在“我的第一个来源”和“我的第二个来源”之后缺少逗号。您的JSON无效。

有效:

{
"name": "Test",
"source": [{
    "name": "my first source",
    "metadata": {
        "name": "testing",
        "products": [{
            "name": "my product",
            "price": 123
        }]
    }
}, {
    "name": "my second source",
    "metadata": {
        "name": "Test",
        "profile": "foo",
        "foo": {
            "foo1": "var1"
        }
    }
}]

}

验证JSON的漂亮工具:

https://jsonlint.com/