Manuel Pena
Manuel Pena

Reputation: 125

Duplicating JSON Key

Is it possible to duplicate a key using Python functions, without transforming it to text/string?

JSON Input

    {
    "lineItems": [
          {
            "sku": "576879",
            "quantity": 2
          }
    ]
}

I would like this output, where the first item is duplicated.

    {
    "lineItems": [
          {
            "sku": "576879",
            "quantity": 2
          },

          **{
            "sku": "576879",
            "quantity": 2
          }**
    ]
}

Thank you!

Upvotes: 1

Views: 86

Answers (1)

BrokenBenchmark
BrokenBenchmark

Reputation: 19242

Yes, you can use .append():

import json

data = json.loads("""{
    "lineItems": [
          {
            "sku": "576879",
            "quantity": 2
          }
    ]
}""")

data["lineItems"].append(data["lineItems"][0])
print(data["lineItems"])

This outputs:

[{'sku': '576879', 'quantity': 2}, {'sku': '576879', 'quantity': 2}]

Upvotes: 3

Related Questions