やりたいこと
下記のjsonのデータからmessageIdを取得したいです。
jsonファイルからデータを取得しようと考えています。
Jsonファイル
{ "tokens": [ "ocho" ], "page": 1, "totalCount": 2, "recordCount": 2, "hasMore": false, "isLimited": false, "records": [ { "roomId": 12345678, "messageId": 2267504144, "writerId": 12119639, "contentType": "post", "text": "ocho1\n1", "createdAt": "2022-05-17T02:09:28.043Z", "updatedAt": "2022-05-17T02:09:28.066Z", "commentCount": 0, "pollId": -1, "postId": -1, "todoId": -1, "from": "web", "isThreaded": false, "mentions": [], "post": { "id": 2267504144, "title": "ocho1", "body": "1" }, "target": { "from": 2267504944, "id": 2267504944, "contentType": "post", "title": "ocho1\n1", "roomId": 12345678, "contentTypeId": 2267504944, "linkId": 2260934186 } }, { "roomId": 12345678, "messageId": 2262505687, "writerId": 12119639, "contentType": "post", "text": "ocho2\n2", "createdAt": "2022-05-17T02:09:36.271Z", "updatedAt": "2022-05-17T02:09:36.289Z", "commentCount": 0, "pollId": -1, "postId": -1, "todoId": -1, "from": "web", "isThreaded": false, "mentions": [], "post": { "id": 2267505687, "title": "ocho2", "body": "2" }, "target": { "from": 2267505687, "id": 2267505687, "contentType": "post", "title": "ocho2\n2", "roomId": 12345678, "contentTypeId": 2267505687, "linkId": 2260934940 } } ] }
実現結果
取り出したいキーはmessageIdを1個ずつです。
messageId:2267504144 messageId:2262505687
現在は下記のコードでやってみましたが、
For分で行うと1個ずつ取り出したいですが上手く取得出来ないです。
コードの原因と解決策を教えていただけると嬉しいです。
import json json_open = open("C:\\Users\\Desktop\\test.json", 'r') json_load = json.load(json_open) print(json_load) #messageId取得方法 for分なし #messageId = json_load["records"][0]["messageId"] #messageId = json_load["records"][1]["messageId"] #print(messageId) #messageId取得方法 for分あり 1個ずつ for key in json_load["records"]["*"]["messageId"]: print(key)
エラー内容
Traceback (most recent call last): File "c:\Users\test\Documents\test_json.py", line 14, in <module> for key in json_load["records"]["*"]["messageId"]: TypeError: list indices must be integers or slices, not str
お手数ですが、よろしくお願い致します。

回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/05/17 07:40
2022/05/17 10:46