#python #json
#python #json
Вопрос:
nestedData = """{"dashboardId":8,"evalMatches":[{"value":1,"metric":"newdb.count { creation_date: 2020-11-26 10:29:13 indicator_label: BBP 1H market: ORN/USDT }","tags":{"creation_date":"2020-11-26 10:29:13","indicator_label":"BBP 1H","market":"ORN/USDT"}},{"value":1,"metric":"newdb.count { creation_date: 2020-11-26 10:29:13 indicator_label: STOCHRSI 1H market: UTK/BTC }","tags":{"creation_date":"2020-11-26 10:29:13","indicator_label":"STOCHRSI 1H","market":"UTK/BTC"}},{"value":1,"metric":"newdb.count { creation_date: 2020-11-26 10:29:13 indicator_label: STOCHRSI 4H market: ORN/USDT }","tags":{"creation_date":"2020-11-26 10:29:13","indicator_label":"STOCHRSI 4H","market":"ORN/USDT"}}],"orgId":1,"panelId":14,"ruleId":52,"ruleName":"test alert","ruleUrl":"http://localhost:3000/d/1xBsMrIMk/alert?tab=alertu0026editPanel=14u0026orgId=1","state":"alerting","tags":{},"title":"[Alerting] test alert"}"""
Я ищу способ извлечь соответствующие «market» и «indicator_label». Я использовал этот код, но он выполняет только один шаг извлечения:
json_obj = json.loads(cts)
market = (json_obj["evalMatches"][0]["tags"]["market"])
indicator_label = (json_obj["evalMatches"][1]["tags"]["indicator_label"])
creation_date = (json_obj["evalMatches"][0]["tags"]["creation_date"])
Мне нужен такой результат
market='ORN/USDT',indicator_label'BBP 1H,STOCHRSI 4H'
market='UTK/USDT',indicator_label'STOCHRSI 1H'
Ответ №1:
Вы можете попробовать:
import json
nestedData = """{"dashboardId":8,"evalMatches":[{"value":1,"metric":"newdb.count { creation_date: 2020-11-26 10:29:13 indicator_label: BBP 1H market: ORN/USDT }","tags":{"creation_date":"2020-11-26 10:29:13","indicator_label":"BBP 1H","market":"ORN/USDT"}},{"value":1,"metric":"newdb.count { creation_date: 2020-11-26 10:29:13 indicator_label: STOCHRSI 1H market: UTK/BTC }","tags":{"creation_date":"2020-11-26 10:29:13","indicator_label":"STOCHRSI 1H","market":"UTK/BTC"}},{"value":1,"metric":"newdb.count { creation_date: 2020-11-26 10:29:13 indicator_label: STOCHRSI 4H market: ORN/USDT }","tags":{"creation_date":"2020-11-26 10:29:13","indicator_label":"STOCHRSI 4H","market":"ORN/USDT"}}],"orgId":1,"panelId":14,"ruleId":52,"ruleName":"test alert","ruleUrl":"http://localhost:3000/d/1xBsMrIMk/alert?tab=alertu0026editPanel=14u0026orgId=1","state":"alerting","tags":{},"title":"[Alerting] test alert"}"""
data = json.loads(nestedData)
output = {}
for val in data["evalMatches"]:
if val["tags"]["market"] not in output:
output[val["tags"]["market"]] = []
output[val["tags"]["market"]].append(str(val["tags"]["indicator_label"]))
for data in output:
print("market='" data "',indicator_label'" ",".join(output[data]) "'" )
Вывод:
market='ORN/USDT',indicator_label'BBP 1H,STOCHRSI 4H'
market='UTK/BTC',indicator_label'STOCHRSI 1H'
Комментарии:
1. Не вывод, запрошенный @navid
2. @AbhigyanJaiswal: измененный ответ