Home > OS >  how to parse this json data in python
how to parse this json data in python

Time:09-30

I have the following JSON for example like this:

{
  "name": "test",
  "version": "0.2.0",
  "lock": 1,
  "requires": true,
  "dependencies": {
    "@yamm/double": {
      "version": "7.14.5",
      "requires": {
        "@ginu/highlight": "^7.4.5"
      }
    },
    "@dauh/data": {
      "version": "7.15.0",
    },
    "@babel/core": {
      "version": "7.12.3",
      "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.12.3.tgz",
      "integrity": "sha512-0qXcZYKZp3/6N2jKYVxZv0aNCsxTSVCiK72DTiTYZAu7sjg73W0/aynWjMbiGd87EQL4WyA8reiJVh92AVla9g==",
      "requires": {
        "@babel/traverse": "^7.12.1",
        "@babel/types": "^7.12.1",
        "convert-source-map": "^1.7.0",
        "debug": "^4.1.0",
        "gensync": "^1.0.0-beta.1",
        "json5": "^2.1.2",
        "lodash": "^4.17.19",
        "resolve": "^1.3.2",
        "semver": "^5.4.1",
        "source-map": "^0.5.0"
      },

I only want to print the data inside requires using Python

I am trying different ways but it's not working. Please help. How shall I do it ?

CodePudding user response:

You can use python's json library to parse your json.

import json

my_json = //your json statement

parsed_json = my_json.loads()

print(parsed_json["requires"])

CodePudding user response:

Looks like you need a recursive approach to this problem. Try this:-

import json

D = '''
{
    "name": "test",
    "version": "0.2.0",
    "lock": 1,
    "requires": true,
    "dependencies": {
        "@yamm/double": {
            "version": "7.14.5",
            "requires": {
                "@ginu/highlight": "^7.4.5"
            }
        },
        "@dauh/data": {
            "version": "7.15.0"
        },
        "@babel/core": {
            "version": "7.12.3",
            "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.12.3.tgz",
            "integrity": "sha512-0qXcZYKZp3/6N2jKYVxZv0aNCsxTSVCiK72DTiTYZAu7sjg73W0/aynWjMbiGd87EQL4WyA8reiJVh92AVla9g==",
            "requires": {
                "@babel/traverse": "^7.12.1",
                "@babel/types": "^7.12.1",
                "convert-source-map": "^1.7.0",
                "debug": "^4.1.0",
                "gensync": "^1.0.0-beta.1",
                "json5": "^2.1.2",
                "lodash": "^4.17.19",
                "resolve": "^1.3.2",
                "semver": "^5.4.1",
                "source-map": "^0.5.0"
            }
        }
    }
}
'''

j = json.loads(D)

def requires(d):
    for k, v in d.items():
        if k == 'requires':
            if isinstance(v, dict):
                for _k, _v in v.items():
                    print(f'{_k}: {_v}')
            else:
                print(f'{k}: {v}')
        else:
            if isinstance(v, dict):
                requires(v)


requires(j)
  • Related