【问题标题】:Need help to format a python dictionary string需要帮助格式化 python 字典字符串
【发布时间】:2018-04-05 15:32:02
【问题描述】:

我无法将下载的文件转换为字典对象,以便访问每个元素。我认为阻止我使用 json_loads() 等的键缺少引号。请您帮我解决一些问题。我在下面给出了下载的结果。我需要格式化它。

{
    success: true,
    results: 2,
    rows: [{
        Symbol: "LITL",
        CompanyName: "LancoInfratechLimited",
        ISIN: "INE785C01048",
        Ind: "-",
        Purpose: "Results",
        BoardMeetingDate: "26-Sep-2017",
        DisplayDate: "19-Sep-2017",
        seqId: "102121067",
        Details: "toconsiderandapprovetheUn-AuditedFinancialResultsoftheCompanyonstandalonebasisfortheQuarterendedJune30,2017."
    }, {
        Symbol: "PETRONENGG",
        CompanyName: "PetronEngineeringConstructionLimited",
        ISIN: "INE742A01019",
        Ind: "-",
        Purpose: "Results",
        BoardMeetingDate: "28-Sep-2017",
        DisplayDate: "21-Sep-2017",
        seqId: "102128225",
        Details: "Toconsiderandapprove,interalia,theUnauditedFinancialResultsoftheCompanyforthequarterendedonJune30,2017."
    }]
}

【问题讨论】:

  • 您可以控制这些数据的生成吗?你能确保它是作为有效的 JSON 生成的吗?
  • 如果您尝试将其解析为 JSON,则需要将属性名称用引号括起来,例如"符号":"LITL"
  • 看起来您正在访问一些 API,但这就是返回的内容。如果是这种情况,您需要先解析并重新格式化该字符串,然后才能将其解析为 JSON。
  • 我无法控制数据。我从一个 URL 得到这个。有没有办法可以用 url 下载 json 数据
  • 是的。我现在如何有选择地格式化以在引号中包含属性名称

标签: string python-2.7 dictionary


【解决方案1】:

如果你有一个字典字符串,这是一种方法。这有点hacky,但应该很好用。

import json
import re

regex_string = '(\w{1,}(?=:))'
regex = re.compile(regex_string, re.MULTILINE)
string = open('test_string', 'r').read() # I had the string in a file, but how
# just put the value here based on how you already had it stored.
string = regex.sub(r'"\1"', string)
python_object = json.loads(string)
# Now you can access the python_object just like any normal python dict.
print python_object["results"]

这是通过正则表达式后的字典。现在你可以用 json 读入它了

{
    "success": true,
    "results": 2,
    "rows": [{
        "Symbol": "LITL",
        "CompanyName": "LancoInfratechLimited",
        "ISIN": "INE785C01048",
        "Ind": "-",
        "Purpose": "Results",
        "BoardMeetingDate": "26-Sep-2017",
        "DisplayDate": "19-Sep-2017",
        "seqId": "102121067",
        "Details": "toconsiderandapprovetheUn-AuditedFinancialResultsoftheCompanyonstandalonebasisfortheQuarterendedJune30,2017."
    }, {
        "Symbol": "PETRONENGG",
        "CompanyName": "PetronEngineeringConstructionLimited",
        "ISIN": "INE742A01019",
        "Ind": "-",
        "Purpose": "Results",
        "BoardMeetingDate": "28-Sep-2017",
        "DisplayDate": "21-Sep-2017",
        "seqId": "102128225",
        "Details": "Toconsiderandapprove,interalia,theUnauditedFinancialResultsoftheCompanyforthequarterendedonJune30,2017."
    }]
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多