Python convert json to python object and visit attribute using comma
<p>As title, A json object or convert to a python object like:</p>

<pre><code>u = {
    "name": "john",
    "coat": {
        "color": "red",
        "sex": "man",
    },
    "groups": [
        {"name": "git"},
        {"name": "flask"}
    ]
}
</code></pre>

<p>I want visit as:</p>

<pre><code>u.name 
</code></pre>

<p>It's easy to do with inherit from dict, but </p>

<pre><code>u.groups.0.name 
</code></pre>

<p>We also set it as </p>

<pre><code>u.name = "flask"
u.groups.0.name = "svn"
</code></pre>

<p>Thanks</p>

<p>May be it's difficult, because integer as key is invalid.</p>

<p>I do like this  </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>class Dict(dict):
    def __init__(self, value):
        if isinstance(value, (list, tuple)):
            value = dict(zip(['_%s' % i for i in range(len(value))], value))
            super(Dict, self).__init__(value)

    def __getattr__(self, key):
        try:
            if type(self.__getitem__(key)) in (dict, OrderedDict, tuple, list):
                return Dict(self.__getitem__(key))
            return self.__getitem__(key)
        except KeyError:
            raise AttributeError(key)

    def __setattr__(self, key, value):
        try:
            return self.__setitem__(key, value)
        except KeyError:
            raise AttributeError(key)</code></pre>
</div>
</div>
</p>

<pre><code>u = {
    "name": "john",
    "coat": {
        "color": "red",
        "sex": "man",
    },
    "groups": [
        {"name": "git"},
        {"name": "flask"}
    ]
}

&gt;&gt;&gt; u = Dict(u)
&gt;&gt;&gt; u.name 
output: john
&gt;&gt;&gt; u.groups._0 
output: {"name": "git"} 
</code></pre>

python