【问题标题】:Parsing a json file - Python解析 json 文件 - Python
【发布时间】:2017-07-16 21:00:56
【问题描述】:

我有一个 Json 文件,我想从中提取特定数据。下面是 JSON 文件:

{
    "results": [ {
        "alternatives": [ {
            "word_confidence": [
                [ "Ryan", 0.335 ],
                [ "how's", 0.589 ],
                [ "the", 1.0 ],
                [ "weather", 1.0 ],
                [ "in", 1.0 ],
                [ "New", 1.0],
                [ "York", 0.989 ],
                [ "today", 0.987 ]
            ],
            "confidence": 0.795,
            "transcript": "Ryan how's the weather in New York today "
        } ],
        "final": true
    } ],
    "result_index": 0
}

使用 python,我如何解析这个文件并提取“成绩单”?

【问题讨论】:

  • import json; data=json.loads(json_string)
  • @stephen 我用过'import json; data = json.loads(json_string)' 返回 '{u'results': [{u'alternatives': [{u'transcript': u"Ryan 今天纽约天气怎么样", u'confidence': 0.795 , u'word_confidence': [[u'Ryan', 0.335], [u"how's", 0.589], [u'the', 1.0], [u'weather', 1.0], [u'in', 1.0 ], [u'New', 1.0], [u'York', 0.989], [u'today', 0.987]]}], u'final': True}], u'result_index': 0}' 现在我必须提取键值“成绩单”的数据..如何做到这一点
  • 找到这个数据的解决方案 = json.loads(json_data) text_data = data["results"][0]["alternatives"][0]["transcript"]

标签: python json python-2.7 parsing


【解决方案1】:

要将json 字符串转换为字典,请使用json.loads()。然后要获取成绩单,只需参考dict,例如:

代码:

import json
data = json.loads(json_string)
transcript = data['results'][0]['alternatives'][0]['transcript']

测试数据:

json_string = """
{
    "results": [ {
        "alternatives": [ {
            "word_confidence": [
                [ "Ryan", 0.335 ],
                [ "how's", 0.589 ],
                [ "the", 1.0 ],
                [ "weather", 1.0 ],
                [ "in", 1.0 ],
                [ "New", 1.0],
                [ "York", 0.989 ],
                [ "today", 0.987 ]
            ],
            "confidence": 0.795,
            "transcript": "Ryan how's the weather in New York today "
        } ],
        "final": true
    } ],
    "result_index": 0
}
"""

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 2015-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多