1

I have a json file as follows:

    {
    "Alib": {
            "depends": null,
            "locked": false,
            "stage": "xyz",
            "version": "1.2.3"
        }
    "Blib": {
            "depends": null,
            "locked": false,
            "stage": "abc",
            "version": "4.3.8"
        }
    "clib": {
            "depends": null,
            "locked": false,
            "stage": "def",
            "version": "5.2.6"
        }
    }

Now i want to read this json file in a way that i get the lib name and the version with respect to that lib. Currently i have solution as follows:

    with open (jsonfile) as data_file:
                file = json.load(data_file)
            print file["alib"]["version"]
            print file["blib"]["version"]
            print file["clib"]["version"]

I do get the details of the each lib version but this is not exactly what i want. I dont want to provide the name of the lib hardcoded into the code. It should be something like :

  with open (jsonfile) as data_file:
                file = json.load(data_file)
      print file[lib]["version"]

and i get the names of the lib along with there versions independently. So, please suggest how shall i acheive this kind of solution where i don't provide the names of the libs and make more generic.

Learner
  • 453
  • 13
  • 29

3 Answers3

2

Once your json is stored into the variable "file", you can iterate through it to print each element.

for lib in file:
    print lib, file[lib]["version"]
1

You json file is loaded as a dict. Each key is a library name, values are dict:

import json
import io

content = '''\
{
    "Alib": {
            "depends": null,
            "locked": false,
            "stage": "xyz",
            "version": "1.2.3"
        },
    "Blib": {
            "depends": null,
            "locked": false,
            "stage": "abc",
            "version": "4.3.8"
        },
    "clib": {
            "depends": null,
            "locked": false,
            "stage": "def",
            "version": "5.2.6"
        }
}'''

fp = io.BytesIO(content)  # can be a real file
json_obj = json.load(fp)

You can display the libraries versions like this:

for lib, attrs in json_obj.items():
    print(u"{lib}: version={version}".format(lib=lib, version=attrs["version"]))

You get:

Alib: version=1.2.3
Blib: version=4.3.8
clib: version=5.2.6
Laurent LAPORTE
  • 21,958
  • 6
  • 58
  • 103
0

The .keys() function should come in handy.

with open (jsonfile) as data_file:
     file = json.load(data_file)
     for key in file.keys():
         print file[key]["version"]

See related questions such as python JSON only get keys in first level for more details.

Community
  • 1
  • 1
wwl
  • 2,025
  • 2
  • 30
  • 51