Better way convert json to SQLAlchemy object
<p>These days I am learning SQLAlchemy. When I want to load an object from json and save it to MySQL, things get difficult because the fields in my model are more that 20 and I wonder whether there're better ways to do this.</p>

<p>My original code follows as an example:</p>

<pre><code>class User(Base):
    __tablename__ = 'parent'
    id = Column(Integer, primary_key=True)
    name = Column(String)

json_str = """{"id": 1, "name": "yetship"}"""
obj = json.loads(json_str)
user = User(id=obj.get("id"), name=obj.get("name"))
</code></pre>

<p>It can work but as I add more fields, it gets awful.</p>

<p>If you have in your json file only fields that you can initialize your <code>User</code> from. Then you simply can do.</p>

<pre><code>user = User(**obj)
</code></pre>

<p><code>**obj</code> will unpack your <code>dict</code> object, so if have <code>obj = {'id': 1, 'name': 'Awesome'}</code>, <code>User(**obj)</code> will do like <code>User(id=1, name='Awesome')</code></p>

<p>You can see <a href="https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists" rel="nofollow">the docs</a></p>

<p>NOTE: it's better to avoid using <code>id</code> as a variable|field, because <code>'id' in dir(__builtin__)</code>, so <code>id</code> in bultins</p>

<p><strong>UPD</strong></p>

<p>If you have in your json fields that don't belong to that model you can filter them out with dict comprehension</p>

<pre><code>user = User(**{k:v for k, v in obj.items() if k in {'id', 'name'}})
</code></pre>

python json sqlalchemy