亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將 json.loads 解析為字符串轉換為字典 python

如何將 json.loads 解析為字符串轉換為字典 python

飲歌長嘯 2023-01-04 10:19:07
標題可能具有誤導性。我有一個要加載的 json 文件,如下所示:{"parent": [  {"venue": "SE",   "city": "some name",   "Rating": 2,   "location": {"x": 100.0, "y": 1.0},   "pubMillis": 1581373546000}  ], "startTime": "2020-02-12 00:00:00:000", "endTime": "2020-02-12 00:01:00:000"}{"parent": [  {"venue": "PP",   "city": "some name 2",   "Rating": 2,   "location": {"x": 101.0, "y": 2.0},   "pubMillis": 1581373546000}  ], "startTime": "2020-02-12 00:00:00:000", "endTime": "2020-02-12 00:05:00:000"}如圖所示,每個parent鍵都由分隔。\n我想讀這個,這是我的代碼:with open('filename.json', 'r') as content_file:    content = content_file.read()records = json.loads(json.dumps(content))print(type(records)) #return as str如果我寫records = json.loads(content),我會得到以下錯誤:json.decoder.JSONDecodeError:額外數據:第 2 行第 1 列(字符 517)因此,json.loads(json.dumps(content))似乎工作。但是,我了解到轉換dumps->loads將返回 asstr而不是dict. 因此,我無法訪問諸如此類的項目,records["parents"]["location"]因為它們是字符串形式的。那么,如何通過轉換str為訪問內部項目dict?
查看完整描述

1 回答

?
30秒到達戰場

TA貢獻1828條經驗 獲得超6個贊

這是問題


看起來要么你有多個子文件,要么{.....}是一個 json


要么


那些({.....})應該在一個數組中......我已經在數組方法下面展示了


a = '''{"parent": [

  {"venue": "SE", 

  "city": "some name", 

  "Rating": 2, 

  "location": {"x": 100.0, "y": 1.0}, 

  "pubMillis": 1581373546000}

  ], 

"startTime": "2020-02-12 00:00:00:000", 

"endTime": "2020-02-12 00:01:00:000"

}

{"parent": [

  {"venue": "PP", 

  "city": "some name 2", 

  "Rating": 2, 

  "location": {"x": 101.0, "y": 2.0}, 

  "pubMillis": 1581373546000}

  ], 

"startTime": "2020-02-12 00:00:00:000", 

"endTime": "2020-02-12 00:05:00:000"

}'''

a = [i.strip() if i.strip()!='}' else i.strip()+',' for i in a.split('\n') ]

a = '\n'.join(a)

a= '[\n'+a[:-1]+'\n]'

import json 

a=json.loads(a) 

print(a)

[{'endTime': '2020-02-12 00:01:00:000',

  'parent': [{'Rating': 2,

    'city': 'some name',

    'location': {'x': 100.0, 'y': 1.0},

    'pubMillis': 1581373546000,

    'venue': 'SE'}],

  'startTime': '2020-02-12 00:00:00:000'},

 {'endTime': '2020-02-12 00:05:00:000',

  'parent': [{'Rating': 2,

    'city': 'some name 2',

    'location': {'x': 101.0, 'y': 2.0},

    'pubMillis': 1581373546000,

    'venue': 'PP'}],

  'startTime': '2020-02-12 00:00:00:000'}]

這就是您獲取數據的方式


a=json.loads(a) 

#print(a)

print(a[0]['parent'][0]['location'])

{'x': 100.0, 'y': 1.0}

如果你想將文件讀入內存


a = "".join([i for i in open('yourFileLocation','r').readlines()])

現在你a在內存中有一個多行字符串


查看完整回答
反對 回復 2023-01-04
  • 1 回答
  • 0 關注
  • 112 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號