如何获取json数组中的最后一个值

问题描述 投票:0回答:1

如何获取 json 数组中的最后一个值。

行=

 {'title': 'Consolidated form', 'question_type': 'year_of_birth_question', 'tags': 'test-form', 'slug': 'test-form', 'version': 'v1.01', 'locale': 'en', 'high_result_page': 'assessment-result-high', 'high_inflection': '50', 'medium_result_page': '0', 'medium_inflection': 'assessment-result-moderate', 'low_result_page': '30', 'skip_threshold': 'assessment-result-low', 'skip_high_result_page': '1', 'generic_error': 'skip-result-page', 'question': 'Oops, something strange happened. Please try again. If this keeps happening, contact Engineering.', 'explainer': 'What year were you born in', 'error': '', 'min': '', 'max': '', 'answers': '', 'scores': '', 'answer_semantic_ids': '', 'question_semantic_id': '', 'None': ['yob-question']}

我的应用程序有时无法检索如上所示的最后一个关键元素,因此我希望能够获取最后一个值(yob-question)并让用户知道没有为 yob-question 检索到关键值。

我不是在寻找硬编码的解决方案,因为列表中的最后一个元素可能并不总是

yob-question

谢谢

我尝试这样打印:

print(row[-1])
但这会返回一个关键错误。

python arrays json dictionary
1个回答
0
投票

我花了一分钟来清理你的代码,我不完全确定你在寻找什么,但我认为这可能有用,或者至少让你朝着正确的方向前进:

import json

data = {
'title': 'Consolidated form',
'question_type': 'year_of_birth_question',
'tags': 'test-form',
'slug': 'test-form',
'version': 'v1.01',
'locale': 'en',
'high_result_page': 'assessment-result-high',
'high_inflection': '50',
'medium_result_page': '0',
'medium_inflection': 'assessment-result-moderate',
'low_result_page': '30',
'skip_threshold': 'assessment-result-low',
'skip_high_result_page': '1',
'generic_error': 'skip-result-page',
'question': 'Oops, something strange happened. Please try again. If this   keeps happening, contact Engineering.',
'explainer': 'What year were you born in',
'error': '',
'min': '',
'max': '',
'answers': '',
'scores': '',
'answer_semantic_ids': '',
'question_semantic_id': '',
'None': ['yob-question']
}

检查“None”键的值及其内容

  if 'None' in data and is instance(data['None'], list) and 'yob-question' in data['None']:
    print("The key 'None' contains 'yob-question'.")
 else:
    print("The key 'None' does not contain 'yob-question'.")

打印词典

 print(json.dumps(data, indent=4))
© www.soinside.com 2019 - 2024. All rights reserved.