import json


def add_to_entry(conn, key, add_name, add_value):
    """
    Find 'key' in consul.
    Treat its value as a JSON string representing a dict.
    Extend the dict by adding an entry with key 'add_name' and value 'add_value'.
    Turn the resulting extended dict into a JSON string.
    Store the string back into Consul under 'key'.
    Watch out for conflicting concurrent updates.

    Example:
    Key 'xyz:dmaap' has the value '{"feed00": {"feed_url" : "http://example.com/feeds/999"}}'
    add_to_entry('xyz:dmaap', 'topic00', {'topic_url' : 'http://example.com/topics/1229'})
    should result in the value for key 'xyz:dmaap' in consul being updated to
    '{"feed00": {"feed_url" : "http://example.com/feeds/999"}, "topic00" : {"topic_url" : "http://example.com/topics/1229"}}'
    """
    while True:     # do until update succeeds
        (index, val) = conn.kv.get(key)     # index gives version of key retrieved

        if val is None:     # no key yet
            vstring = '{}'
            mod_index = 0   # Use 0 as the cas index for initial insertion of the key
        else:
            vstring = val['Value']
            mod_index = val['ModifyIndex']

        # Build the updated dict
        # Exceptions just propagate
        v = json.loads(vstring)
        v[add_name] = add_value
        new_vstring = json.dumps(v)

        updated = conn.kv.put(key, new_vstring, cas=mod_index)       # if the key has changed since retrieval, this will return false
        if updated:
            return v