Python JSON parse duplicate records

前端 未结 1 1395
野趣味
野趣味 2021-01-22 18:14

In my JSON file I have sequence of same-named records

\"ability_upgrades\":{
    \"ability\":5155,
    \"time\":1226
},
\"ability_upgrades\":{
    \"ability\":51         


        
相关标签:
1条回答
  • 2021-01-22 19:17

    The documentation says a parameter called object_pairs_hook in json.loads can be used for handling duplicated records:

    >>> json.loads(s, object_pairs_hook=(lambda x:  x))
    [(u'ability_upgrades', [(u'ability', 5155), (u'time', 1226)]), (u'ability_upgrades', [(u'ability', 5155), (u'time', 1426)]), (u'ability_upgrades', [(u'ability', 5155), (u'time', 1497)]), (u'ability_upgrades', [(u'ability', 5157), (u'time', 1543)])]
    

    How that function is defined is totally depending on what you want it to be. In the example above, since that hook gets as parameters a list of pairs, the identity function simply gives the list back.

    E.g., if you define:

    def collectAbilityUpgrades(s):
        d = {}
        for k, v in s:
            if k not in d:
                d[k] = []
            d[k].append(v)
        return d
    

    Then:

    >>> json.loads(s, object_pairs_hook=collectAbilityUpgrades)
    {u'ability_upgrades': [{u'ability': [5155], u'time': [1226]}, {u'ability': [5155], u'time': [1426]}, {u'ability': [5155], u'time': [1497]}, {u'ability': [5157], u'time': [1543]}]}
    

    Which probably is similar to what you want.

    0 讨论(0)
提交回复
热议问题