Monday, December 5, 2016

Parsing values from Json

12/5/16

http://stackoverflow.com/questions/2835559/parsing-values-from-a-json-file-in-python


[] are for lists, {} are for dictionaries.
Here's how your JSON file should look:
{
    "maps": [
        {
            "id": "blabla",
            "iscategorical": "0"
        },
        {
            "id": "blabla",
            "iscategorical": "0"
        }
    ],
    "masks": {
        "id": "valore"
    },
    "om_points": "value",
    "parameters": {
        "id": "valore"
    }
}
Then you can use your code:
import json
from pprint import pprint

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

pprint(data)
- With data, you can now also find values like so:
data["maps"][0]["id"] ...... here [0] because maps has values in [..]. If [0] not used it will throw string - int error.
data["masks"]["id"]
data["om_points"]
 

- How I can get the number of elements in node of JSON data?




down vote
accepted
import json

json_data = json.dumps({
  "result":[
    {
      "run":[
        {
          "action":"stop"
        },
        {
          "action":"start"
        },
        {
          "action":"start"
        }
      ],
      "find": "true"
    }
  ]
})

item_dict = json.loads(json_data)
print len(item_dict['result'][0]['run'])
Convert it in dict.

3 comments:

  1. How to handle json key errors in json??

    ReplyDelete
  2. How to identify, which key failed in python key error??

    ReplyDelete
    Replies

    1. https://stackoverflow.com/questions/23139024/which-key-failed-in-python-keyerror

      Delete