0
votes

I would like to compare two json values like

source1 = 
{ "a" : "value 1",
 "b" : "value to be updated", 
"c" : "value 3",
 "d" : "second value to be updated" 
  }

target = { 
    "a" : "value 1",  
   "b" : "value 2"",    
   "c" : "value 3",  
   "d" : "second 4"}

Now , I would like to compare both the json which will have same key but values may differ . How can I find the differed value?

My end result should look like :

{
"a" : "value 1"
"b" : "value 2"
"c" : "value 3"
"d" : "second4"

}

In the code the first set of key:value needs to be compared with second set and if the second set contains different values , then update the key:value and create a third json set :

import json
source = '{"a" : "value 1","b" : "value to be updated","c" : "value 3","d" : "second value to be updated" }'

target = '{"a": "value1" , "b" : 2 , "c" : "value 3" , "d" : 4}'

jsonload = (json.loads(source))
jsonload1 = (json.loads(target))

for k in jsonload:
    for k in jsonload1:
        if jsonload[k] != jsonload1[k]:
            print("key of" , k ,"not matched in ", k ,jsonload[k],jsonload1[k])

output :

('key of', u'a', 'not matched in ', u'a', u'value 1', u'value1') ('key of', u'b', 'not matched in ', u'b', u'value to be updated', 2) ('key of', u'd', 'not matched in ', u'd', u'second value to be updated', 4) ('key of', u'a', 'not matched in ', u'a', u'value 1', u'value1') ('key of', u'b', 'not matched in ', u'b', u'value to be updated', 2) ('key of', u'd', 'not matched in ', u'd', u'second value to be updated', 4) ('key of', u'a', 'not matched in ', u'a', u'value 1', u'value1') ('key of', u'b', 'not matched in ', u'b', u'value to be updated', 2) ('key of', u'd', 'not matched in ', u'd', u'second value to be updated', 4) ('key of', u'a', 'not matched in ', u'a', u'value 1', u'value1') ('key of', u'b', 'not matched in ', u'b', u'value to be updated', 2) ('key of', u'd', 'not matched in ', u'd', u'second value to be updated', 4)

1
Take a moment to read through the editing help in the help center. Formatting on Stack Overflow is different than other sites. The better your post looks, the easier it is for others to read and understand it.Patrick Artner
"I would like to compare two json value" => those are NOT "json values", those are Python dicts. Read the doc for python's dicts and you'll find all you need.bruno desthuilliers

1 Answers

1
votes

Looks like you need dict.update() method

Ex:

source1 = { "a" : "value 1", "b" : "value to be updated", "c" : "value 3", "d" : "second value to be updated" }
target = { "a" : "value 1", "b" : "value 2", "c" : "value 3", "d" : "second 4"}
source1.update(target)
print(source1)

Output:

{'a': 'value 1', 'c': 'value 3', 'b': 'value 2', 'd': 'second 4'}