2015-05-29 48 views
-1

我在Python中工作,我有以JSON格式存儲的數據。 我想編譯對應於某個鍵的所有數據。例如。從Python中的JSON數據編譯多個關鍵內容

{"menu": { 
    "header": "SVG Viewer", 
    "items": [ 
     {"id": "Open"}, 
     {"id": "OpenNew", "label": "Open New"}, 
     null, 
     {"id": "ZoomIn", "label": "Zoom In"}, 
     {"id": "ZoomOut", "label": "Zoom Out"}, 
     {"id": "OriginalView", "label": "Original View"}, 
     null, 
     {"id": "Quality"}, 
     {"id": "Pause"}, 
     {"id": "Mute"}, 
     null, 
     {"id": "Find", "label": "Find..."}, 
     {"id": "FindAgain", "label": "Find Again"}, 
     {"id": "Copy"}, 
     {"id": "CopyAgain", "label": "Copy Again"}, 
     {"id": "CopySVG", "label": "Copy SVG"}, 
     {"id": "ViewSVG", "label": "View SVG"}, 
     {"id": "ViewSource", "label": "View Source"}, 
     {"id": "SaveAs", "label": "Save As"}, 
     null, 
     {"id": "Help"}, 
     {"id": "About", "label": "About Adobe CVG Viewer..."} 
    ] 
}} 

我想將所有「標籤」鍵的內容編譯到列表中。

有沒有辦法做到這一點,沒有「往樹下」,這是不必遍歷包含鍵(「菜單」>>「項」「」標籤「)?

最好,我正在尋找一個基於JSON的解決方案,而不是使用REGEX來定位內容的一個技巧。

+3

不,你將不得不* *「沿着樹」*。不過,樹['menu'] ['items']]中的項目[item ['label']]似乎並不那麼痛苦。 – jonrsharpe

+0

基於JSON的解決方案? JSON是一種數據格式,而不是代碼。 – martineau

回答

0

您可以使用jsonpath_rw

import json 
from jsonpath_rw import parse 

d = json.loads("""{"menu": { 
     "header": "SVG Viewer", 
     "items": [ 
      {"id": "Open"}, 
      {"id": "OpenNew", "label": "Open New"}, 
      null, 
      {"id": "ZoomIn", "label": "Zoom In"}, 
      {"id": "ZoomOut", "label": "Zoom Out"}, 
      {"id": "OriginalView", "label": "Original View"}, 
      null, 
      {"id": "Quality"}, 
      {"id": "Pause"}, 
      {"id": "Mute"}, 
      null, 
      {"id": "Find", "label": "Find..."}, 
      {"id": "FindAgain", "label": "Find Again"}, 
      {"id": "Copy"}, 
      {"id": "CopyAgain", "label": "Copy Again"}, 
      {"id": "CopySVG", "label": "Copy SVG"}, 
      {"id": "ViewSVG", "label": "View SVG"}, 
      {"id": "ViewSource", "label": "View Source"}, 
      {"id": "SaveAs", "label": "Save As"}, 
      null, 
      {"id": "Help"}, 
      {"id": "About", "label": "About Adobe CVG Viewer..."} 
     ] 
    }}""") 

    get_labels = parse("menu.items[*].label") 

    for match in get_labels.find(d): 
     print match.value # value of label 

注意,這基本上是使用「下去的樹」爲您服務,但其更高層次的界面使得它更容易使用。