[英]Using ast.literal_eval on a nested dictionary
我正在使用 ast.literal_eval 將我從 json.loads() 接收到的數據更改為 Python 字典; 但是,如果我應該以完全不同的方式處理這個問題 - 也請隨時指出這一點。
# Authentication
buf = StringIO.StringIO()
c = pycurl.Curl()
c.setopt(c.URL, "https://kippt.com/api/account")
c.setopt(c.WRITEFUNCTION, buf.write)
c.setopt(c.HTTPHEADER, header)
c.perform()
result = buf.getvalue()
buf.close()
print result
# Printing Output
data_string = json.dumps(result)
jsonload = json.loads(data_string)
jsondict = ast.literal_eval(jsonload)
目前它可以通過一行 JSON 返回正常工作,例如:
{"username": "my_username", "api_token": "my_api_token"}
我可以通過以下方式正確獲取值:
print jsondict['username']
print jsondict['api_token']
我遇到問題的部分是數據嵌套時,例如:
{"meta": {"next": null, "total_count": 6, "previous": null, "limit": 20, "offset": 0}, "objects": [{"rss_url": "https: //kippt.com/feed/username_here/stuff_here/cool-stuff", "updated": "1339003710", "title": "Cool Stuff", "created": "1339001514", "slug": "cool-stuff" ", "id": 54533, "resource_uri": "/api/lists/54533/"}, {"rss_url": "https://kippt.com/feed/username_here/stuff_here/programming", "更新": "1339003479", "title": "Programming", "created": "1339001487", "slug": "programming", "id": 54532, "resource_uri": "/api/lists/54532/"}, { "rss_url": "https://kippt.com/feed/username_here/stuff_here/android", "updated": "1339003520", "title": "Android", "created": "1339000936", "slug": “android”,“id”:54530,“resource_uri”:“/api/lists/54530/”},{“rss_url”:“https://kippt.com/feed/username_here/stuff_here/chrome”,“更新": "1339000931", "title": "Chrome", "created": "1339000412", "slug": "chrome", "id": 54529, "resource_uri": "/api/lists/54529/"} , {"rss_url": "https://kippt.com/feed/use rname_here/stuff_here/inbox", "updated": "1338946730", "title": "收件箱", "created": "1338945940", "slug": "inbox", "id": 54432, "resource_uri": " /api/lists/54432/"}, {"rss_url": "https://kippt.com/feed/username_here/stuff_here/read-later", "updated": "1338945940", "title": "稍后閱讀", "created": "1338945940", "slug": "read-later", "id": 54433, "resource_uri": "/api/lists/54433/"}]}
當我使用相同的代碼(/api/lists 的 Exchange URL)時,運行腳本時出現以下錯誤:
回溯(最近一次調用):文件“kippt.py”,第 48 行,在 jsondict = ast.literal_eval(jsonload) 文件“/usr/local/lib/python2.7/ast.py”,第 80 行,在literal_eval return _convert(node_or_string) File "/usr/local/lib/python2.7/ast.py", line 63, in _convert in zip(node.keys, node.values)) File "/usr/local/lib/python2 .7/ast.py”,第 62 行,返回 dict((_convert(k), _convert(v)) for k, v 文件“/usr/local/lib/python2.7/ast.py”,第 63 行, in _convert in zip(node.keys, node.values)) File "/usr/local/lib/python2.7/ast.py", line 62, in return dict((_convert(k), _convert(v) ) for k, v File "/usr/local/lib/python2.7/ast.py", line 79, in _convert raise ValueError('malformed string') ValueError: malformed string
任何幫助,將不勝感激。 謝謝!
看起來我的第一個輸入可能被解釋為 Python 語法,這就是我的錯所在,因為我在技術上沒有以正確的方式開始。
我現在只想 json.loads() 我從 cURL 得到的結果,而不是做我以前做的那些棘手的事情。
例如:
buf = StringIO.StringIO()
c = pycurl.Curl()
c.setopt(c.URL, "https://kippt.com/api/lists")
c.setopt(c.WRITEFUNCTION, buf.write)
c.setopt(c.HTTPHEADER, header)
c.perform()
result = buf.getvalue()
buf.close()
print result
# Printing Output
jsonload = json.loads(result)
print jsonload['meta']['total_count'] # Gets the total_count item in the meta object.
ast.literal_eval
對嵌套字典沒有問題:
>>> ast.literal_eval("{'a': {'b':'c'}}")
{'a': {'b': 'c'}}
ast.literal_eval
正在破壞,因為數據實際上是 JSON……而且 JSON 不是有效的 Python。 具體來說, null
不是有效的 Python 文字。
為什么不直接使用json.loads()
來加載數據?
我想出了一個場景,我想在 Pandas 中使用 json.normalize 但值是 str 類型的。 使用 ast.literal_eval,我輸入類型轉換
你可以像下面這樣使用 ast.literal_eval - df[column_name] = df[column_name].apply(ast.literal_eval)
這會將 str 轉換為 dict。 例如。 df = [{'A': "{'value': '1'}", 'B': "{'value': '2'}"}]
應用文字 eval 后 - df = [{'A': {'value': '1'}, 'B': {'value': '2'}}]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.