【问题标题】:python: retrieve a section of JSON data, without knowing the structurepython:在不知道结构的情况下检索一段 JSON 数据
【发布时间】:2017-04-14 13:32:51
【问题描述】:

我有这个 JSON:

 {u'spreadsheetId': u'19CugmHB1Ds6n1jBy4Zo4hk_k4sQsTmOFfccxRc2qo', 
    u'properties': {u'locale': u'en_US', u'timeZone': u'Asia/Hong_Kong',
    u'autoRecalc': u'ON_CHANGE', u'defaultFormat': {u'padding': {u'top': 2, u'right': 3, u'left': 3, u'bottom': 2}, u'textFormat': {u'foregroundColor': {}, u'bold': False, u'strikethrough': False, u'fontFamily': u'arial,sans,sans-serif', u'fontSize': 10, u'italic': False, u'underline': False}, u'verticalAlignment': u'BOTTOM', u'backgroundColor': {u'blue': 1, u'green': 1, u'red': 1}, u'wrapStrategy': u'OVERFLOW_CELL'}, u'title': u'test pygsheets API V4'}, u'sheets': [{u'properties': {u'sheetType': u'GRID', u'index': 0, u'sheetId': 0, u'gridProperties': {u'columnCount': 26, u'rowCount': 1000}, u'title': u'IO'}}, {u'basicFilter': {u'range': {u'endRowIndex': 978, u'startRowIndex': 2, u'sheetId': 1704577069, u'startColumnIndex': 1, u'endColumnIndex': 9}, u'sortSpecs': [{u'sortOrder': u'ASCENDING', u'dimensionIndex': 1}, {u'sortOrder': u'ASCENDING', u'dimensionIndex': 4}, {u'sortOrder': u'ASCENDING', u'dimensionIndex': 5}, {u'sortOrder': u'ASCENDING', u'dimensionIndex': 8}, {u'sortOrder': u'ASCENDING', u'dimensionIndex': 3}, {u'sortOrder': u'ASCENDING', u'dimensionIndex': 7}, {u'sortOrder': u'ASCENDING', u'dimensionIndex': 2}]}, u'properties': {u'sheetType': u'GRID', u'index': 1, u'title': u'books', u'gridProperties': {u'columnCount': 22, u'rowCount': 978, u'frozenColumnCount': 3, u'hideGridlines': True, u'frozenRowCount': 3}, u'tabColor': {u'blue': 1}, u'sheetId': 1704577069}}], u'spreadsheetUrl': u'https://docs.google.com/spreadsheets/d/1CugmHB1Ds6n1jBy4Zo4hk_k4sQsTmOFfccxRc2qo/edit'}

如何从 JSON 中仅获取 sheetstitles?我想要类似的东西

输入:results.get('title')

输出:['IO','books']

由于嵌套结构,我什至不知道如何处理它。这让人想起 html 节点类型结构。所以我需要某种类型的搜索功能?

有没有办法在不查看结构的情况下到达title 节点?有点像 xpath 搜索类型函数?我以前用过beautifulsoup,你可以不知道结构,通过搜索取出部分数据。

【问题讨论】:

  • 到目前为止你尝试过什么?您在尝试代码时遇到了什么问题?
  • 您应该包含您尝试过的代码。这与嵌套字典没有什么不同
  • 其实它字典,不是JSON。
  • 您为什么在示例输出中排除IO
  • 对不起...错误,已编辑

标签: python json data-structures


【解决方案1】:

这将给出你想要的输出:

print [x['properties'].get('title') for x in results['sheets']]

返回:[u'IO', u'books']

【讨论】:

  • 我必须知道properties 是结构的一部分......你能在不知道properties 的情况下做到吗?
  • @jason 有可能,是的,但通常使用 JSON,您需要提前知道对象的结构。 JSON 解析器不附带 xpath 等效项。你需要这样的东西(我以前没用过):pypi.python.org/pypi/jsonpath-rw
【解决方案2】:

这应该可行:

a = {your json/dict?}
print(a['properties']['title']) # prints 'test pygsheets API V4'
print(a['sheets'][0]['properties']['title']) #prints 'IO'
print(a['sheets'][1]['properties']['title']) # prints 'books'

编辑: 对于未知结构:

def find_in_obj(obj, condition, path=None):

    if path is None:
        path = []

    # In case this is a list
    if isinstance(obj, list):
        for index, value in enumerate(obj):
            new_path = list(path)
            for result in find_in_obj(value, condition, path=new_path):
                yield result

    # In case this is a dictionary
    if isinstance(obj, dict):
        for key, value in obj.items():
            new_path = list(path)
            for result in find_in_obj(value, condition, path=new_path):
                yield result

            if condition == key:
                new_path = list(path)
                new_path.append(value)
                yield new_path

results = []
for item in find_in_obj(a, 'title'):
    results.append(item)
print(results) #prints [['test pygsheets API V4'], ['IO'], ['books']]

修改自:合瑞软件解决方案Find all occurrences of a key in nested python dictionaries and lists

【讨论】:

  • 里面有多个title键。
  • 如果我知道结构...如果我不想看结构而只想搜索titles怎么办?我正在寻找一个通用的解决方案。
  • 您的编辑已硬编码解决方案。如果字典很大,您需要某种for 循环或输入时非常耐心。
  • @roganjosh 你是说你的编辑器没有宏支持? :P
  • 我添加了递归解决方案
猜你喜欢
  • 2015-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多