SimpleJson handling of same named entities

后端 未结 2 902
北海茫月
北海茫月 2020-12-04 00:29

I\'m using the Alchemy API in app engine so I\'m using the simplejson library to parse responses. The problem is that the responses have entries that have the sme name

2条回答
  •  一个人的身影
    2020-12-04 01:00

    The rfc 4627 that defines application/json says:

    An object is an unordered collection of zero or more name/value pairs
    

    And:

    The names within an object SHOULD be unique.
    

    It means that AlchemyAPI should not return multiple "subType" names inside the same object and claim that it is a JSON.

    You could try to request the same in XML format (outputMode=xml) to avoid ambiguity in the results or to convert duplicate keys values into lists:

    import simplejson as json
    from collections import defaultdict
    
    def multidict(ordered_pairs):
        """Convert duplicate keys values to lists."""
        # read all values into lists
        d = defaultdict(list)
        for k, v in ordered_pairs:
            d[k].append(v)
    
        # unpack lists that have only 1 item
        for k, v in d.items():
            if len(v) == 1:
                d[k] = v[0]
        return dict(d)
    
    print json.JSONDecoder(object_pairs_hook=multidict).decode(text)
    

    Example

    text = """{
      "type": "Person",
      "subType": "Athlete",
      "subType": "AwardWinner"
    }"""
    

    Output

    {u'subType': [u'Athlete', u'AwardWinner'], u'type': u'Person'}
    

提交回复
热议问题