簡體   English   中英

將 JSON 文件中的數據轉換為 Python dict

[英]Converting data inside a JSON file into Python dict

我有一個 JSON 文件,它的內部看起來像這樣:

"{'reviewId': 'gp:AOqpTOGiJUWB2pk4jpWSuvqeXofM9B4LQQ4Iom1mNeGzvweEriNTiMdmHsxAJ0jaJiK7CbjJ_s7YEWKE2DA_Qzo', 'userName': '\u00c0ine Mongey', 'userImage': 'https://play-lh.googleusercontent.com/a-/AOh14GhUv3c6xHP4kvLSJLaRaydi6o2qxp6yZhaLeL8QmQ', 'content': \"Honestly a great game, it does take a while to get money at first, and they do make it easier to get money by watching ads. I'm glad they don't push it though, and the game is super relaxing and fun!\", 'score': 5, 'thumbsUpCount': 2, 'reviewCreatedVersion': '1.33.0', 'at': datetime.datetime(2021, 4, 23, 8, 20, 34), 'replyContent': None, 'repliedAt': None}"

我正在嘗試將其轉換為 dict,然后轉換為 Pandas DataFrame。 我試過這個,但它只會把它變成一個 dict 的字符串表示,而不是一個 dict 本身:

with open('sampledict.json') as f:
    dictdump = json.loads(f.read())
    print(type(dictdump))

我覺得我現在離得很近了,但我無法找出我想念的東西來從中得到什么。 任何輸入將不勝感激!

如果我正確獲取您的數據格式,這將起作用:

with open('sampledict.json') as f:
    d = json.load(f)
d = eval(d)

# Or this works as well
    d = json.loads(f.read())
d = eval(d)
>>> d.keys()
['userName', 'userImage', 'repliedAt', 'score', 'reviewCreatedVersion', 'at', 'replyContent', 'content', 'reviewId', 'thumbsUpCount']

您確定您的源 JSON 正確嗎? 您提供的 JSON 片段一個字符串; 它的開頭和結尾都有一個" 。因此,在當前形式中,獲取字符串是正確的行為。

另請注意,它是 Python dict 的字符串表示形式,而不是 JSON 對象。 字符串由單引號而不是雙引號表示,以及使用 Python 關鍵字None而不是 JSON null就證明了這一點。

如果 JSON 文件是一個普通對象的代表,那么內容將是以下形式:

{
  "reviewId": "gp"AO...",
  "userName": "...",
  "replyContent": null,
  "repliedAt": null
}

即第一個和最后一個字符是花括號,而不是雙引號。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM