-2

I have the json file and its content is like in the below. I have a code for read and parse it. You can see my code in the below.

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

my code

with open('data2.json', 'w') as jsonFile:
    json.dump(str(output_array), jsonFile)
    jsonFile.close()
 
 
mySql_insert_query = """INSERT INTO wmi_inventory (wmi_data, date) 
                                VALUES (%s, %s) """
now = datetime.now()
dt_string = now.strftime("%Y-%m-%d-%H:%M:%S")
record = (data, dt_string)
cursor.execute(mySql_insert_query, record)
connection.commit()
 
with open('data2.json','r') as lst:
     data=lst.read()
     d = json.loads(json.dumps(data))
     print(d["Name"])

When i run my code, im getting this error. How can i solve this?

Traceback (most recent call last):
  File "wmi_deneme.py", line 121, in <module>
    print(d["Name"])
TypeError: string indices must be integers

I have 3 outputs like :

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

I tried to get them all in an array and this is the result. So this is my output array.

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

I want to reach this values Name Manucaturer Username.

i'm stuck here

ayayay
  • 1
  • 1
  • 5
  • 1
    Does this answer your question? [Why am I seeing "TypeError: string indices must be integers"?](https://stackoverflow.com/questions/6077675/why-am-i-seeing-typeerror-string-indices-must-be-integers) – LSeu Mar 10 '22 at 08:58
  • 1
    This is obvious XY problem - at the start when you write to `data2.json` file, you cast `output_array` into string before you write it. There the problem starts. What is `output_array`? Then when you try to read `d = json.loads(json.dumps(data))` you once again first dump the string, then read it as json - complete non-sense. – buran Mar 10 '22 at 08:59
  • See `json.load`. – Thierry Lathuille Mar 10 '22 at 08:59
  • output_array is an array which occurs my outputs. But these outputs are dictionary value. – ayayay Mar 10 '22 at 09:45
  • output array is : ['[{"Manufacturer": "VMware, Inc.", "Model": "VMware7,1", "Name": "DC01"}]', '[{"Index": "1", "IPAddress": ["192.168.1.240,fe80::350e:d28d:14a5:5cbb"]}]', '[{"Name": "DC01", "UserName": null}]'] – ayayay Mar 10 '22 at 09:54
  • Note that `output_array` is still odd , its elements are not dicts - it's a list of strings, each string represents list literal, that list element being a dict. I still think you perform multiple Unnecessary type conversions. Note that deep inside there is `IP` key, that is suppose to be list of IP addresses and it is elements are again single string. Where does `Output_array` come from? – buran Mar 10 '22 at 11:42
  • Also, please, don't add important info in comments - edit your question instead. – buran Mar 10 '22 at 11:48
  • I edit my question, you can look at it. Thank you – ayayay Mar 10 '22 at 11:50

1 Answers1

0
import json
output_array =  [[{'Manufacturer': 'VMware, Inc.', 'Model': 'VMware7,1', 'Name': 'DC01'}],
                 [{'Index': '1', 'IPAddress': ['192.168.1.240', 'fe80::350e:d28d:14a5:5cbb']}],
                 [{'Name': 'DC01', 'UserName': None}]]

# write to json
with open('data.json', 'w') as f:
    json.dump(output_array, f, indent=4)

# reading from JSON
with open('data.json') as f:
    data = json.load(f)
    for item in data:
        for dct in item:
            print('------------------')
            for key in ['Manufacturer', 'Name', 'UserName']:
                print(f"{key} --> {dct.get(key, 'Key Not Present')}") 

Note the change I made to IPAddress - now it is list of strings, not list with single string representing 2 comma-separated IP addresses. But you can keep it single string despite it doesn't make sense.

This will produce following JSON

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

Now, when you have proper JSON file, the reading part (repeated below):

with open('data.json') as f:
    data = json.load(f)
    for item in data:
        for dct in item:
            print('------------------')
            for key in ['Manufacturer', 'Name', 'UserName']:
                print(f"{key} --> {dct.get(key, 'Key Not Present')}") 

this will output

------------------
Manufacturer --> VMware, Inc.
Name --> DC01
UserName --> Key Not Present
------------------
Manufacturer --> Key Not Present
Name --> Key Not Present
UserName --> Key Not Present
------------------
Manufacturer --> Key Not Present
Name --> DC01
UserName --> None

It is bit odd that you have a [unnecessarily] deeply-nested structure like this, why not just list of dicts?

buran
  • 13,682
  • 10
  • 36
  • 61
  • First of all thank you for your answer. I replace my json file with the true one that you suggest me. I run the code below with starting with open which is the second one. I gave an error. print(f"{key} --> {dct.get(key, 'Key Not Present')}") data['Manufacturer']}") ^ SyntaxError: invalid syntax I have python 3.9 – ayayay Mar 10 '22 at 12:45
  • The code works just fine. I will edit my answer to make it one block, to avoid any copy/paste error. – buran Mar 10 '22 at 12:46
  • Can i ask one more question? The json data are coming me in a single quote. But true json format is with " ". How can i replace that ' with " – ayayay Mar 10 '22 at 12:52
  • _The json data are coming me in a single quote._ Where are they coming from? If they come as malformed JSON - fix it at the time when you write it to the JSON file - I showed how to write and how to read. You keep to withhold information. – buran Mar 10 '22 at 13:11