Home > Blockchain >  How can i parse an output like dictionary in python?
How can i parse an output like dictionary in python?

Time:03-10

I have this code.

import json
 
with open('data5.json', 'r') as myfile:
    data = myfile.read()
    data_2 = data.replace('[', ' ')
    data_3 = data_2.replace(']', ' ')
    print(data_3)

My variable data_3 is like that:

{"Manufacturer": "VMware, Inc.", "Model": "VMware7,1", "Name": "DC01"} ,  {"Index": "1", "IPAddress":  "192.168.1.240,fe80::350e:d28d:14a5:5cbb" } 

I want to parse this. I want to get the value of Manufacturer or Model or Name. After parsing i will save them into the database. How can i do it?

CodePudding user response:

Your data is json, so use the json library from the stdlib:

import json
with open('data5.json', 'r') as myfile:
    data = json.load(myfile)

No need to do any manual parsing.

CodePudding user response:

import json
with open('data5.json', 'r') as myfile:
    data = json.load(myfile)
    for i in data:
        print(data['Name'])

I tried this code for getting Name. It gives me error

Traceback (most recent call last):
  File "C:\Users\DELL\AppData\Roaming\JetBrains\PyCharmCE2021.3\scratches\scratch_38.py", line 5, in <module>
    print(data['Name'])
TypeError: list indices must be integers or slices, not str
  • Related