2017-10-12 74 views
1

我嘗試使用mongoengine將一個JSON請求保存到MongoDB中的DynamicDocument時出現問題。無法在DynamicEmbeddedDocument中保存複雜的JSON結構(Mongoengine,Flask)

這裏是我的文檔:

class documentSource(DynamicEmbeddedDocument): 
    name = StringField() 

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

這是我的信息發佈對象:

{ 
     "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" 
      } 
     } 
     ] 
    } 

這裏是我的瓶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中。

非常感謝您的幫助。

回答

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/

+0

沒有遺憾,這是複製和粘貼到這個問題的錯誤,其實我用郵遞員提出要求,郵遞員有驗證員。 –

+0

答案是正確的。你的JSON無效。接受它併發佈一個不同的問題... –