logo

Pythonで文字列をJSONに変換する

このトピックを深く掘り下げる前に、文字列とは何か、JSON とは何かについて簡単に見てみましょう。

文字列: は、逆カンマ '' を使用して示される一連の文字です。これらは不変です。つまり、一度宣言すると変更することはできません。

JSON: 「JavaScript Object Notation」の略で、JSON ファイルは人間が簡単に読めるテキストで構成され、属性と値のペアの形式で存在します。

JSONファイルの拡張子は「.json」です。

Python で文字列を json に変換する最初のアプローチを見てみましょう。

次のプログラムは同じことを示しています。

junit テストケース
 # converting string to json import json # initialize the json object i_string = {'C_code': 1, 'C++_code' : 26, 'Java_code' : 17, 'Python_code' : 28} # printing initial json i_string = json.dumps(i_string) print ('The declared dictionary is ', i_string) print ('It's type is ', type(i_string)) # converting string to json res_dictionary = json.loads(i_string) # printing the final result print ('The resultant dictionary is ', str(res_dictionary)) print ('The type of resultant dictionary is', type(res_dictionary)) 

出力:

 The declared dictionary is {'C_code': 1, 'C++_code' : 26, 'Java_code' : 17, 'Python_code' : 28} It's type is The resultant dictionary is {'C_code': 1, 'C++_code' : 26, 'Java_code' : 17, 'Python_code' : 28} The type of resultant dictionary is 

説明:

私たちの論理を明確にするために、説明を見てみましょう -

キャメルケースパイソン
  1. ここでの目的は文字列を json ファイルに変換することなので、最初に json モジュールをインポートします。
  2. 次のステップでは、サブジェクト名をキーとして持つ json オブジェクトを初期化し、対応する値を指定します。
  3. この後、私たちが使用したのは、 ダンプ() Python オブジェクトを JSON 文字列に変換します。
  4. 最後に、使用します ロード() JSON 文字列を解析して辞書に変換します。

eval() の使用

 # converting string to json import json # initialize the json object i_string = ''' {'C_code': 1, 'C++_code' : 26, 'Java_code' : 17, 'Python_code' : 28} ''' # printing initial json print ('The declared dictionary is ', i_string) print ('Its type is ', type(i_string)) # converting string to json res_dictionary = eval(i_string) # printing the final result print ('The resultant dictionary is ', str(res_dictionary)) print ('The type of resultant dictionary is ', type(res_dictionary)) 

出力:

 The declared dictionary is {'C_code': 1, 'C++_code' : 26, 'Java_code' : 17, 'Python_code' : 28} Its type is The resultant dictionary is {'C_code': 1, 'C++_code': 26, 'Java_code': 17, 'Python_code': 28} The type of resultant dictionary is 

説明:

上記のプログラムで何を行ったかを理解しましょう。

  1. ここでの目的は文字列を json ファイルに変換することなので、最初に json モジュールをインポートします。
  2. 次のステップでは、サブジェクト名をキーとして持つ json オブジェクトを初期化し、対応する値を指定します。
  3. この後、私たちが使用したのは、 eval() Python 文字列を json に変換します。
  4. プログラムを実行すると、目的の出力が表示されます。

値の取得

最後に、最後のプログラムでは、文字列を JSON に変換した後の値を取得します。

見てみましょう。

 import json i_dict = '{'C_code': 1, 'C++_code' : 26, 'Java_code':17, 'Python_code':28}' res = json.loads(i_dict) print(res['C_code']) print(res['Java_code']) 

出力:

 1 17 

出力では次のことがわかります。

  1. json.loads() を使用して文字列を json に変換しました。
  2. この後、キー「C_code」と「Java_code」を使用して、対応する値をフェッチしました。

結論

このチュートリアルでは、Python を使用して文字列を json に変換する方法を学びました。