grow food, not lawn.

Skip to content

Fix wrong-ordered update

Russell Ballestrini requested to merge github/fork/MaximumQuiet/master into master

Created by: MaximumQuiet

Hi all, I found a little bug: when I try to alter this json structure:

{
  "total": 1,
  "data": [{
    "id": "2015-001-093555-258",
    "regDate": "2015-12-22T08:49:29",
    "history": [{
      "id": "2015-001-093555-258",
      "regDate": "2015-12-22T08:49:29",
      "type": "CREATION",
      "link": "/api/search/history/2015-001-093555-258/0?key=306411c9-44c9-4239-a97c-17745368f224"
    }],
    "link": "/api/search/extract/2015-001-093555-258?key=306411c9-44c9-4239-a97c-17745368f224"
  }],
  "key": "306411c9-44c9-4239-a97c-17745368f224"
}

code:

with open("test.json", "rb") as file:
    struc = json.loads(file.read())
    alter = nested_alter(struc, "link", lambda v: v + "###")
    print(alter)

I've got this output:

{
  "total": 1,
  "data": [{
    "id": "2015-001-093555-258",
    "regDate": "2015-12-22T08:49:29",
    "history": [{
      "id": "2015-001-093555-258",
      "regDate": "2015-12-22T08:49:29",
      "type": "CREATION",
      "link": "/api/search/extract/2015-001-093555-258?key=306411c9-44c9-4239-a97c-17745368f224###"
    }],
    "link": "/api/search/history/2015-001-093555-258/0?key=306411c9-44c9-4239-a97c-17745368f224###"
  }],
  "key": "306411c9-44c9-4239-a97c-17745368f224"
}

As you can see, values are reversed.

The problem was in if document.get(key): function. Key link detects in wrong order:

{
  "total": 1,
  "data": [{
    "id": "2015-001-093555-258",
    "regDate": "2015-12-22T08:49:29",
    "history": [{
      "id": "2015-001-093555-258",
      "regDate": "2015-12-22T08:49:29",
      "type": "CREATION",
      "link <- SECOND DETECT": "/api/search/history/2015-001-093555-258/0?key=306411c9-44c9-4239-a97c-17745368f224"
    }],
    "link  <- FIRST DETECT": "/api/search/extract/2015-001-093555-258?key=306411c9-44c9-4239-a97c-17745368f224"
  }],
  "key": "306411c9-44c9-4239-a97c-17745368f224"
}

So, I decided to use current key dict_key == key for update instead of document.get()


Also, I suggest using stack-like values list, instead of run variable. If len(value) less than keys count, then use the last value as default.

if dict_key == key:
    document[key] = value[0]
    if len(value) > 1:
        value.pop(0)

And in conclusion, I haven't understood, why the test, test_nested_update_taco_for_example() should change only first value?

Merge request reports