Home Parsing values from a JSON file?
Reply: 7

Parsing values from a JSON file?

michele
1#
michele Published in 2010-05-14 15:54:20Z

I have this JSON in a file:

{
    "maps": [
        {
            "id": "blabla",
            "iscategorical": "0"
        },
        {
            "id": "blabla",
            "iscategorical": "0"
        }
    ],
    "masks": [
        "id": "valore"
    ],
    "om_points": "value",
    "parameters": [
        "id": "valore"
    ]
}

I wrote this script which prints all of the json text:

json_data=open(file_directory).read()

data = json.loads(json_data)
pprint(data)

How can I parse the file and extract single values?

Community
2#
Community Reply to 2017-11-11 23:47:36Z

I think what Ignacio is saying is that your JSON file is incorrect. You have [] when you should have {}. [] are for lists, {} are for dictionaries.

Here's how your JSON file should look, your JSON file wouldn't even load for me:

{
    "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

data = json.load(open('data.json'))

pprint(data)

With data, you can now also find values like so:

data["maps"][0]["id"]
data["masks"]["id"]
data["om_points"]

Try those out and see if it starts to make sense.

Community
3#
Community Reply to 2017-05-23 12:18:36Z

Your data.json should look like this:

{
 "maps":[
         {"id":"blabla","iscategorical":"0"},
         {"id":"blabla","iscategorical":"0"}
        ],
"masks":
         {"id":"valore"},
"om_points":"value",
"parameters":
         {"id":"valore"}
}

Your code should be:

import json
from pprint import pprint

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

Note that this only works in Python 2.6 and up, as it depends upon the with-statement. In Python 2.5 use from __future__ import with_statement, in Python <= 2.4, see Justin Peel's answer, which this answer is based upon.

You can now also access single values like this:

data["maps"][0]["id"]  # will return 'blabla'
data["masks"]["id"]    # will return 'valore'
data["om_points"]      # will return 'value'
user1743724
4#
user1743724 Reply to 2013-05-12 20:47:46Z
data = []
with codecs.open('d:\output.txt','rU','utf-8') as f:
    for line in f:
       data.append(json.loads(line))
codeforester
5#
codeforester Reply to 2018-02-10 04:45:38Z

"Ultra JSON" or simply "ujson" can handle having [] in your JSON file input. If you're reading a JSON input file into your program as a list of JSON elements; such as, [{[{}]}, {}, [], etc...] ujson can handle any arbitrary order of lists of dictionaries, dictionaries of lists.

You can find ujson in the Python package index and the API is almost identical to Python's built-in json library.

ujson is also much faster if you're loading larger JSON files. You can see the performance details in comparison to other Python JSON libraries in the same link provided.

the Tin Man
6#
the Tin Man Reply to 2016-08-02 23:01:05Z

@Justin Peel's answer is really helpful, but if you are using Python 3 reading JSON should be done like this:

with open('data.json', encoding='utf-8') as data_file:
    data = json.loads(data_file.read())

Note: use json.loads instead of json.load. In Python 3, json.loads takes a string parameter. json.load takes a file-like object parameter. data_file.read() returns a string object.

sushmit
7#
sushmit Reply to 2017-04-25 17:42:50Z

if you are in python 3 here is how you can do it

{
  "connection1": {
    "DSN": "con1",
    "UID": "abc",
    "PWD": "1234",
    "connection_string_python":"test1"
  }
  ,
  "connection2": {
    "DSN": "con2",
    "UID": "def",
    "PWD": "1234"
  }
}

The code should look like assuming connection.json file looks like above

connection_file = open('connection.json', 'r')
conn_string = json.load(connection_file)
conn_string['connection1']['connection_string_python'])
>>>test1
JoboFive
8#
JoboFive Reply to 2017-11-07 01:53:18Z
   # Here you go with modified json file:
   # data.json file : 
    {
        "maps": [
            {
                "id": "blabla",
                "iscategorical": "0"
            },
            {
                "id": "blabla",
                "iscategorical": "0"
            }
        ],
        "masks": [{
            "id": "valore"
        }],
        "om_points": "value",
        "parameters": [{
            "id": "valore"
        }]
    }


   # You can call or print data on console by using below lines

    import json
    from pprint import pprint
    with open('data.json') as data_file:
        data_item = json.load(data_file)
    pprint(data_item)

    print(data_item['parameters'][0]['id'])

    #Output : 
    #pprint(data_item) output as :

    {'maps': [{'id': 'blabla', 'iscategorical': '0'},
              {'id': 'blabla', 'iscategorical': '0'}],
     'masks': [{'id': 'valore'}],
     'om_points': 'value',
     'parameters': [{'id': 'valore'}]}
    #print(data_item['parameters'][0]['id']) output as :
    valore
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.314697 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO