Извлечь поля и их путь из объекта JSON с помощью Python - PullRequest
0 голосов
/ 14 июня 2019

Я получил объект json из сопоставления индексов эластичного поиска. Я хочу сгруппировать поля индекса из объекта json на основе его типа.

https://gist.github.com/akthodu/47404880d2e5b6480a881214d41feb58

длинное поле

act.sdeactLongDescription.properties.id.type
act.properties.actstate.type

текстовое поле:

act.properties.sdeactLongDescription.longDescription.type

Я получаю строковый объект, когда зацикливаюсь на выводе, полученном из json.loads.Есть ли библиотека json для извлечения внутренних элементов, таких как bs4?

1 Ответ

0 голосов
/ 14 июня 2019

Вы можете выполнить рекурсивную функцию и найти конец цепочки, например:

import json

d = open('test.json')
test = json.load(d, strict=False)


# You could add the chain of keys to a list
def recursive_items(dictionary):
    for key, value in dictionary.items():
        if type(value) is dict:
            # Value becomes a sub-dictionary
            yield from recursive_items(value)
        else:
            # End of the chain
            yield (key, value)


if __name__ == "__main__":
    for key, value in recursive_items(test):
        print(key, value)

# Regex might work too (this pattern could prob be improved a lot)

import re
pattern = r'[^,]+"type"[^,]+'
matches = re.findall(pattern, string, re.DOTALL)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...