Python での JSON データ解析
質問:
JSON データを Python に変換する方法オブジェクト?
背景:
Facebook API から JSON データ オブジェクトを受け取り、それをデータベースに保存したいと考えています。現在使用している Django ビューは、次のコードで表されます:
response = request.POST user = FbApiUser(user_id = response['id']) user.name = response['name'] user.username = response['username'] user.save()
これは正常に動作しますが、複雑な JSON データ オブジェクトを処理する方法を知りたいと考えています。使いやすくするために、その JSON オブジェクトを Python オブジェクトに変換する方法があればいいのにと思います。
解決策:
Python 3 では、SimpleNamespace と object_hook を使用してこれを簡単に実行できます。
import json from types import SimpleNamespace data = '{"name": "John Smith", "hometown": {"name": "New York", "id": 123}}' # 将JSON解析为带有对应于dict键的属性的对象。 x = json.loads(data, object_hook=lambda d: SimpleNamespace(**d)) print(x.name, x.hometown.name, x.hometown.id)
Python 2 では、namedtuple を使用できます。
import json from collections import namedtuple data = '{"name": "John Smith", "hometown": {"name": "New York", "id": 123}}' # 将JSON解析为带有对应于dict键的属性的对象。 x = json.loads(data, object_hook=lambda d: namedtuple('X', d.keys())(*d.values())) print x.name, x.hometown.name, x.hometown.id
この関数を簡単に再利用するには、次のコードを使用できます。
def _json_object_hook(d): return namedtuple('X', d.keys())(*d.values()) def json2obj(data): return json.loads(data, object_hook=_json_object_hook) x = json2obj(data)
有効なプロパティ名ではないキーを処理したい場合は、namedtuple の rename パラメータを確認してください。
以上がJSON データを Python オブジェクトに変換するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

forhandlinglaredataSetsinpython、usenumpyArrays forbetterperformance.1)numpyarraysarememory-effictientandfasterfornumericaloperations.2)nusinnnnedarytypeconversions.3)レバレッジベクトル化は、測定済みのマネージメーシェイメージーウェイズデイタイです

inpython、listsusedynamicmemoryallocation with allocation、whilenumpyArraysalocatefixedmemory.1)listsallocatemorememorythanneededededinitivative.2)numpyArrayasallocateexactmemoryforements、rededicablebutlessflexibilityを提供します。

inpython、youcanspecthedatatypeyfelemeremodelernspant.1)usenpynernrump.1)usenpynerp.dloatp.ploatm64、フォーマーpreciscontrolatatypes。

numpyisessentialfornumericalcomputinginpythonduetoitsspeed、memory efficiency、andcomprehensivematicalfunctions.1)それは、performsoperations.2)numpyArraysaremoremory-efficientthanpythonlists.3)Itofderangeofmathematicaloperty

contiguousMemoryAllocationisucial forArraysは、ForeffienceAndfastelementAccess.1)iteenablesConstantTimeAccess、O(1)、DuetodirectAddresscalculation.2)itemprovesefficiencyByAllowingMultiblementFechesperCacheLine.3)itimplifieMememm

slicingapythonlistisdoneusingtheyntaxlist [start:stop:step] .hore'showitworks:1)startisthe indexofthefirstelementtoinclude.2)spotisthe indexofthefirmenttoeexclude.3)staptistheincrementbetbetinelements

numpyallows forvariousoperationsonarrays:1)basicarithmeticlikeaddition、減算、乗算、および分割; 2)AdvancedperationssuchasmatrixMultiplication;

Arraysinpython、特にnumpyandpandas、aresentialfordataanalysis、offeringspeedandeficiency.1)numpyarraysenable numpyarraysenable handling forlaredatasents andcomplexoperationslikemoverages.2)Pandasextendsnumpy'scapabivitieswithdataframesfortruc


ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

ドリームウィーバー CS6
ビジュアル Web 開発ツール

ZendStudio 13.5.1 Mac
強力な PHP 統合開発環境

SublimeText3 中国語版
中国語版、とても使いやすい

SAP NetWeaver Server Adapter for Eclipse
Eclipse を SAP NetWeaver アプリケーション サーバーと統合します。
