Search code examples
pythonjsonsimplejson

Python - convert strings into json and combine


I h've two strings got from an api url

pagehandle = urllib2.urlopen(ariel_url+"?%s"  % params1)
data1 = pagehandle.read(); 
pagehandle = urllib2.urlopen(ariel_url+"?%s"  % params2)
data2 = pagehandle.read(); 

data1 and data2 contain the following string

{"priority":"HIGH", "titles":["Brand", "Likes"], "values":[["addidas", 130],["nike", 180]]}

{"priority":"HIGH", "titles":["Brand", "Likes"], "values":[["iphone", 49],["ipod", 590]]}

I want to convert these two strings into json and combine (or combine strings and then convert) in such a way that output json may like

{"priority":"HIGH", "titles":["Brand", "Likes"], "values":[["addidas", 130],["nike", 180],["iphone", 49],["ipod", 590]]]}

How can i do this? i prefer to use simplejson library


Solution

  • These are not strings, but dictionaries. You can combine those dictionary like this:

    def combine(dict1, dict2):
        if dict1['priority'] == dict2['priority'] and dict1['titles'] == dict2['titles']:
            return {
                'priority': dict1['priority'],
                'titles': dict1['titles'],
                'values': dict1['values'] + dict2['values']
            }
    

    after that you simply run:

    import json
    json.dumps(combine(dict1, dict2))
    

    and you'll get a json of those two combined dictionaries.

    EDIT

    So I understand is what you really got is:

    s1 = '{"priority":"HIGH", "titles":["Brand", "Likes"], values:[["addidas", 130],["nike", 180]]}'
    
    s2 = '{"priority":"HIGH", "titles":["Brand", "Likes"], values:[["iphone", 49],["ipod", 590]]}'
    

    In this case you can run:

    dict1 = json.loads(s1)
    dict2 = json.loads(s2)
    result = combine(dict1, dict2)