質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

解決済

2回答

3047閲覧

PythonでJSONのデータからエクセルへ書き出したい

fideo

総合スコア55

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

0クリップ

投稿2022/05/20 11:28

編集2022/05/24 20:11

やりたいこと
下記のjsonのデータからcreatedAt・title・messageIdの項目を取得しております。
jsonファイルから取得した各項目をエクセルへ貼り付けたいです。

Jsonファイル

{ "tokens": [ "アメリカ" ], "page": 1, "totalCount": 3, "recordCount": 3, "hasMore": false, "isLimited": false, "records": [ { "roomId": 18913457, "messageId": 2276890177, "writerId": 13489639, "contentType": "post", "text": "アメリカ\n1", "createdAt": "2022-05-20T03:53:39.654Z", "updatedAt": "2022-05-20T03:53:39.668Z", "commentCount": 0, "pollId": -1, "postId": -1, "todoId": -1, "from": "web", "isThreaded": false, "mentions": [], "post": { "id": 2276890177, "title": "アメリカ", "body": "1" }, "target": { "from": 2276890177, "id": 2276890177, "contentType": "post", "title": "アメリカ\n1", "roomId": 18913457, "contentTypeId": 2276890177, "linkId": 2270092589 } }, { "roomId": 18913457, "messageId": 2276891330, "writerId": 13489639, "contentType": "post", "text": "アメリカ>ロス\n1", "createdAt": "2022-05-20T03:54:20.650Z", "updatedAt": "2022-05-20T03:54:20.671Z", "commentCount": 0, "pollId": -1, "postId": -1, "todoId": -1, "from": "web", "isThreaded": false, "mentions": [], "post": { "id": 2276891330, "title": "アメリカ>ロス", "body": "1" }, "target": { "from": 2276891330, "id": 2276891330, "contentType": "post", "title": "アメリカ>ロス\n1", "roomId": 18913457, "contentTypeId": 2276891330, "linkId": 2270093714 } }, { "roomId": 18913457, "messageId": 2276891991, "writerId": 13489639, "contentType": "post", "text": "アメリカ>ニューヨーク\n2", "createdAt": "2022-05-20T03:54:40.624Z", "updatedAt": "2022-05-20T03:54:40.657Z", "commentCount": 0, "pollId": -1, "postId": -1, "todoId": -1, "from": "web", "isThreaded": false, "mentions": [], "post": { "id": 2276891991, "title": "アメ\nリカ>ニューヨーク", "body": "2" }, "target": { "from": 2276891991, "id": 2276891991, "contentType": "post", "title": "アメリカ>ニューヨーク\n2", "roomId": 18913457, "contentTypeId": 2276891991, "linkId": 2270094355 } } ] }

実現したエクセルの処理結果
各カラムごとにデータを出力をしたいです。

createdAttitlemessageId
2022-05-20T03:53:39.654Zアメリカ2276890177
2022-05-20T03:54:20.650Zアメリカ>ロス2276891330
2022-05-20T03:54:40.624Zアメリカ>ニューヨーク2276891991

現在の結果
全てのリストが1行のみに書き出しされます。
各カラム・行ごとにデータを出力するにはどのようにdataを変更すれば良いでしょうか。
もし分かる方がいましたら、教えていただけると幸いです。

createdAttitlemessageId
['2022-05-20T03:53:39.654Z', '2022-05-20T03:54:20.650Z', '2022-05-20T03:54:40.624Z']['アメリカ', 'アメリカ>ロス', 'アメ\nリカ>ニューヨーク'][2276890177, 2276891330, 2276891991]

全体のコード

import json import pandas as pd #jsonファイル読み込み json_open = open("C:\\Users\\test\\Desktop\\test.json", 'r') json_load = json.load(json_open) print(json_load) #エクセルファイル excelfile="C:\\Users\\test\\Desktop\\test.xlsx" #作成日時取得 createdAt= [x["createdAt"] for x in json_load["records"]] print(createdAt) #['2022-05-20T03:53:39.654Z', '2022-05-20T03:54:20.650Z', '2022-05-20T03:54:40.624Z'] #タイトル取得 title= [x["post"]["title"] for x in json_load["records"]] print(title) #['アメリカ', 'アメリカ>ロス', 'アメリカ>ニューヨーク'] #メッセージID取得 messageId= [x["messageId"] for x in json_load["records"]] print(messageId) #[2276890177, 2276891330, 2276891991] #Header作成 col = ["createdAt","title","messageId"] #Headerのみdataframe作成 df = pd.DataFrame(columns=col) #dataframe作成 data = {'createdAt' : createdAt, 'title' : title, 'messageId' : messageId} #新しい行に値を追加 df_new = df.append(data, ignore_index=True) #xlsx書き出し df_new.to_excel(excelfile, sheet_name="sheet", index=False, header=True)

お手数ですが、よろしくお願い致します。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答2

0

pandas.json_normalize を使う方法です。

python

1import pandas as pd 2import json 3 4pd.set_option('display.unicode.east_asian_width', True) 5 6with open('test.json') as f: js = json.load(f) 7df = pd.json_normalize(js, 'records')[['createdAt', 'post.title', 'messageId']]\ 8 .rename(columns=lambda x: x.split('.')[-1]) 9 10#df.to_excel('test.xlsx', sheet_name='sheet', index=False, header=True) 11print(df) 12 13# 14 createdAt title messageId 150 2022-05-20T03:53:39.654Z アメリカ 2276890177 161 2022-05-20T03:54:20.650Z アメリカ>ロス 2276891330 172 2022-05-20T03:54:40.624Z アメ\nリカ>ニューヨーク 2276891991

投稿2022/05/20 15:15

編集2022/05/20 15:35
melian

総合スコア19618

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

fideo

2022/05/23 04:04

ありがとうございます。こちらの方法も応用の時には参考致します。 すいません、私にとってlamda関数まだ難しいです。
melian

2022/05/23 04:25

> 私にとってlamda関数まだ難しいです。 それは残念な事です。なお、 rename(columns=lambda x: x.split('.')[-1]) の部分は post.title を title に変更しているだけです。カラム名がそのままでよいのであれば、 df = pd.json_normalize(js, 'records')[['createdAt', 'post.title', 'messageId']] だけで構いません。
guest

0

ベストアンサー

jsonの中身を何度もループして、各列に対応する値のリストを作っていくのは管理が大変ですし、列数が増えれば増えるほど、コードが煩雑になっていきます。
なので、ディクショナリーを内包するリストからpandas.DataFrameを作成する方法で試してみました。ファイルのパスは任意のものに変更して試してみて下さい。

python

1import json 2import pandas as pd 3 4def to_excel_dict(record): 5 return { 6 'created_at': record['createdAt'], 7 'title': record['post']['title'], 8 'messageId': record['messageId'] 9 } 10 11json_load = json.load(open(".jsonファイルへのpath")) 12df_data = [ to_excel_dict(record) for record in json_load['records'] ] 13df = pd.DataFrame(data=df_data) 14df.to_excel("出力する.xlsxのパス", sheet_name="sheet", index=False, header=True)

参考

https://www.self-study-blog.com/dokugaku/python-pandas-dataframe-make/#1%E8%A1%8C%E3%81%9A%E3%81%A4%E8%BE%9E%E6%9B%B8%E3%81%A7%E4%BD%9C%E6%88%90%E3%81%99%E3%82%8B%E6%96%B9%E6%B3%95

投稿2022/05/20 14:27

okabe-yuya

総合スコア23

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

fideo

2022/05/23 04:03

ありがとうございます。 こちらの方法が一番分かりやすかったです。
okabe-yuya

2022/05/24 11:11

そう言って頂けて何よりです🙏
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問