0

I seem to be hitting a strange blocker trying to access some data items in a JSON data structure.

I need to iterate over the items within the data array in within the JSON but can't work out how to get to them.

I've tried this:

import json
from pprint import pprint

file = 'data.json'

with open(file) as data_file:
    data = json.load(data_file)

for host in data:
    print host["host"]

    for proto in host["protocols"]:
        print proto

This gets me my protocol versions, but I can't work out how to get to the items in the data array.

[
  {
    "host": "192.168.0.1",
    "port": 443,
    "protocols": {
      "v1": {
        "data": ["12345","54354334534253245342"],
        "tag": "abc"
      },
      "v2": {
        "data": ["45678"],
        "tag": "xyz"
      }
    },
    "processed": false
  },
  {
    "host": "192.168.0.3",
    "port": 443,
    "protocols": {
      "v1": {
        "data": ["12345","43434","543543543"],
        "tag": "abc"
      },
      "v2": {
        "data": ["45678"],
        "tag": "xyz"
      },
      "v3": {
        "data": ["910111"],
        "tag": "ttt"
      }
    },
    "processed": false
  }
]

1 Answer 1

5

Protocols is a dictionary, so you would need to iterate it a bit differently:

import json
from pprint import pprint

file = 'data.json'

with open(file) as data_file:
    data = json.load(data_file)

for host in data:
    print host["host"]

    for version, proto in host["protocols"].iteritems():
        print version
        print proto
        print proto["data"]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.