0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Python】カンマ( , )がついた状態でJSONにシリアライズすると配列になる

Posted at

概要

Pythonのコードでなぜか意図せず配列(リスト)になってしまいました。
単なる一文字のタイプミスでしたが、備忘として残します。

原因

以下のように、タイプミスで「,」が入っていることに気づかずコードをデプロイしてしまっていました。

sample_name = f"{hoge}{foo}",

すると、Python側でタプル型とされてしまい、
JSONシリアライズ時にタプルがリストとして変換され、

sample_name = [f"{hoge}{hoge}"]

のように配列(リスト)として返されてしまっていたのです。

実際に以下のようなコードでprintしてみると、、

import json


hoge = "hoge"
foo = "foo"

sample_name = f"{hoge}{foo}",
print(sample_name)  # Output: ('hogefoo',)

json_str = json.dumps({"sample_name": sample_name})
print(json_str)  # Output: {"sample_name": ["hogefoo"]}

確かにjson.dumpsでJSON形式にエンコードすると、["hogefoo"]というように配列になっていることがわかります。

VScodeでも特に赤い波線とか出てくれないから、一見すると見落としがちです...

以上!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?