0

So, I want to change my info in json file from python, but I am having trouble. my json file is just info that I want to edit later:

[
  {
    "codigo": 10,
    "Nom_articulo": "jabon",
    "valor": 2500,
    "cantidad": 6,
    "subtotal": 0,
    "descuento": 0
  },
  {
    "codigo": 20,
    "Nom_articulo": "Crema",
    "valor": 9800,
    "cantidad": 4,
    "subtotal": 0,
    "descuento": 0
  },
  {
    "codigo": 30,
    "Nom_articulo": "Cepillo",
    "valor": 6000,
    "cantidad": 7,
    "subtotal": 0,
    "descuento": 0
  },
  {
    "codigo": 40,
    "Nom_articulo": "Servilletas",
    "valor": 3000,
    "cantidad": 2,
    "subtotal": 0,
    "descuento": 0
  },
  {
    "codigo": 50,
    "Nom_articulo": "Desodorante",
    "valor": 5000,
    "cantidad": 6,
    "subtotal": 0,
    "descuento": 0
  }
]

I want to change the value of "subtotal" in all my dictionaries.

so basically what I did was:

for i in range(len(archivo_r)):
                precio= archivo_r[i]["valor"]
                cantidad=archivo_r[i]["cantidad"]
                subtotal=precio*cantidad
                print(archivo_r[i]["codigo"], " - " ,archivo_r[i]["Nom_articulo"], " = ", str(subtotal))
                #almacenar mis subtotales en el archivo json
                print("sbtotal" ,archivo_r[i]["subtotal"])
                archivo_r[i]["subtotal"]=subtotal
                #archivo_r[i]["subtotal"].append(subtotal)
                #print(archivo_r)
            write_json(**XXXXX**)

This part of the code: archivo_r[i]["subtotal"]=subtotal does exactly what I need, but (and this could be very silly, but I am a little lost here) I do not know how to use that to re-write my json file. I mean, I have the function to write it.

def write_json(info, nombre_archivo="productos.json"):
    with open(nombre_archivo, "w") as p:
        json.dump(info, p)

I need to pass the information in write_json(**XXXXX**), but have been trying to storage my archivo_r[i]["subtotal"]=subtotal in a variable to pass it and other things, but nothing work. I know I am doing wrong but not sure how to solve it.

1 Answer 1

1

Once you're done processing the data, simply pass archivo_r to your write_json() function and you should be fine.

As an aside, you can iterate directly over the JSON objects like so:

for section in archivo_r:
    precio = section["valor"]
    ...

You can then replace all instances of archivo_r[i] with section, or whatever you want to call the variable.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.