简体   繁体   中英

extract data from json with python

Bear with me, I'm totally new in python :-) and this my first ever question here. I've been looking around here and wasn't able to find the answer. I'm sorry in advance if this has been answered already; if so, please point me in the right direction:-)

I've got this json file, named export.json

Here the contents:

{"10.0": ["mp-cacao", 32.0, 2.1], "38.0": ["mp-sucre", 36.0, 1.9], "36.0": ["mp-farine", 40.0, 0.5], "37.0": ["mp-lait", 44.0, 3.0], "40.0": ["heures M-O", 48.0, 10.0], "39.0": ["heures machine", 52.0, 0.7]}

-The numbers between quotes (10.0, 38.0 etc) are databases ids (this is an extract of an Odoo database (CRM/ERP tool)

-"mp-cacao", "mp-sucre", etc are the name

-32.0, 36.0 etc are the quantities (that's the field i'm interested on)

I've been trying to come up with a python code for

  1. reading this data
  2. most importantly, to be able to extract the first number between the square brackets to be able to send this number back to a database

So far I was able to read the file or some specific entry in the file with the following code

import json

with open("export.json") as json_file:
    json_data = json.load(json_file)
    print (json_data)

or to read a specific entry, example the first one

import json

with open("export.json") as json_file:
    json_data = json.load(json_file)
    print (json_data['10.0'])

The code above returns this

['mp-cacao', 32.0, 2.1]

Finally the question: how can I extract and use just the second number in each entry = the quantities?

for key, value in json_data.items():
    print(key, value[1])

You will get id and the second value in your list. Is that what you are going to achieve?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM