【问题标题】:I am trying to map a json string to a dictionary我正在尝试将 json 字符串映射到字典
【发布时间】:2016-10-27 00:02:35
【问题描述】:

我使用这个字符串作为参数 "{'totalCount':'1','ID':'1029','IP':'10.0.0.1'}"

它应该返回一个包含以下值的字典

result[“totalCount”]: 值为 '1'

result[“ID”]: 值为 '1029'

result[“IP”]: 值为 '10.0.0.1'

我的代码有什么问题?

import json
example_string = "{'totalCount':'1','ID':'1029', 'IP':'10.0.0.1'}"
result = json.loads(example_string)

print(result["'totalCount','ID','IP'"])

【问题讨论】:

  • 您的代码有什么问题?描述您遇到的问题。
  • result 是您的字典,您尝试访问的那些键不存在。使用 json 对象中的键
  • "'totalCount','ID','IP'" 是单键,您的字典中没有此键。
  • 这是我得到的错误:文件“python”,第 3 行,在 ValueError: Expecting property name: line 1 column 2 (char 1)

标签: python json string dictionary


【解决方案1】:

你有两个错误

首先:您必须使用双引号 " 而不是 ' 才能正确格式化 JSON。

第二个:"'totalCount','ID','IP'" 是单键,字典中没有这个键

import json

example_string = '{"totalCount": "1", "ID": "1029", "IP": "10.0.0.1"}'
result = json.loads(example_string)

print('totalCount:', result['totalCount'])
print('ID:', result['ID'])
print('IP:', result['IP'])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-23
    • 1970-01-01
    • 2011-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多