Home > Software engineering >  Python JSON append
Python JSON append

Time:11-09

I'm trying to find out how to format my json file for my puprose.

My json file looks like this (pulled from sql db):

[
    {
        "type": "xy",
        "view_code": "english",
        "short": "xy",
        "product": "simple",
        "amount": "4"
    },
]

what I am trying to achive is something like this:


[
{
  "products":**   {
        "type": "N1001",
        "view_code": "english",
        "short": "xy",
        "product": "simple",
        "amount": "4"
    }
}
]

how can I add {"products": at the beginning and } at the end of my json file? So the main object is "products":

Thanks in advance! Wayx

EDIT:

I'm trying to achive something like this:

[
{
  "products":   
{
        "type": "N1001",
        "view_code": "english",
        "short": "xy",
        "product": "simple",
        "amount": "4"
    },
{
        "type": "N1001",
        "view_code": "english",
        "short": "xy",
        "product": "simple",
        "amount": "4"
    }
}
]

CodePudding user response:

ao = array of object

ao = [ { "type": "xy", "view_code": "english", "short": "xy", "product": "simple", "amount": "4" }]

print(ao)
arr = []

for el in ao:
    vals = {}
    vals[el['product']]=el
    arr.append(vals)
    
print(arr)

where:

vals[el['product']]=el

is the value, which needs to be positioned as key.


Edit:

ao = [ { "type": "xy", "view_code": "english", "short": "xy", "product": "simple", "amount": "4" }, { "type": "xy", "view_code": "english", "short": "xy", "product": "simple", "amount": "4" }]

arr = {}
arr['products'] = ao

output:

{'products': [{'type': 'xy', 'view_code': 'english', 'short': 'xy', 'product': 'simple', 'amount': '4'}, {'type': 'xy', 'view_code': 'english', 'short': 'xy', 'product': 'simple', 'amount': '4'}]}

CodePudding user response:

Do you have a JSON file or a list of dictionaries? If you have a JSON file, you'll first want to load the JSON into Python datastructures like so:

import json

data = json.loads(my_string)

You can then do this:

new_data = [{"products": item} for item in data]

If you need to convert it back to JSON you can then do this:

my_string = json.dumps(new_data)
  • Related