zzz
zzz

Reputation: 517

unable to update JSON using python

I am trying to update transaction ID from the following json:

{
    "locationId": "5115",
    "transactions": [
        {
            "transactionId": "1603804404-5650",
            "source": "WEB"
        } ]

I have done following code for the same, but it does not update the transaction id, but it inserts the transaction id to the end of block:-

 try:
        session = requests.Session()
        with open(
                "sales.json",
                "r") as read_file:
            payload = json.load(read_file)

            payload["transactionId"] = random.randint(0, 5)
        with open(
                "sales.json",
                "w") as read_file:
            json.dump(payload, read_file)

Output:-

{
    "locationId": "5115",
    "transactions": [
        {
            "transactionId": "1603804404-5650",
            "source": "WEB"
        } ]
}
'transactionId': 1
}

Expected Outut:-

{
    "locationId": "5115",
    "transactions": [
        {
            "transactionId": "1",
            "source": "WEB"
        } ]

Upvotes: 0

Views: 69

Answers (3)

Mohammad Amin
Mohammad Amin

Reputation: 62

Yes because transactionId is inside transactions node. So your code should be like:

payload["transactions"][0].transactionId = random.randint(0, 5)

or

payload["transactions"][0]["transactionId"] = random.randint(0, 5)

Upvotes: 0

Chase
Chase

Reputation: 5615

If you just want to find the transactionId key and you don't know exactly where it may exist. You can do-

from collections.abc import Mapping

def update_key(key, new_value, jsondict):
    new_dict = {}
    for k, v in jsondict.items():
        if isinstance(v, Mapping):
            # Recursive traverse if value is a dict
            new_dict[k] = update_key(key, new_value, v)
        elif isinstance(v, list):
            # Traverse through all values of list
            # Recursively traverse if an element is a dict
            new_dict[k] = [update_key(key, new_value, innerv) if isinstance(innerv, Mapping) else innerv for innerv in v]
        elif k == key:
            # This is the key to replace with new value
            new_dict[k] = new_value
        else:
            # Just a regular value, assign to new dict
            new_dict[k] = v
    return new_dict

Given a dict-

{
    "locationId": "5115",
    "transactions": [
        {
            "transactionId": "1603804404-5650",
            "source": "WEB"
        } ]
}

You can do-

>>> update_key('transactionId', 5, d)
{'locationId': '5115', 'transactions': [{'transactionId': 5, 'source': 'WEB'}]}

Upvotes: 0

Sedy Vlk
Sedy Vlk

Reputation: 565

This would do it, but only in your specific case:

payload["transactions"][0]["transactionId"] = xxx

There should be error handling for cases like "transactions" key is not int the dict, or there are no records or there are more than one

also, you will need to assign =str(your_random_number) not the int if you wish to have the record of type string as the desired output suggests

Upvotes: 2

Related Questions