+2 votes
2 views
in Python by (3.9k points)
edited by

This my my JSON:

{
    "maps": [
        {
            "id": "AT",
            "iscategorical": "0"
        },
        {
            "id": "AT",
            "iscategorical": "0"
        }
    ],
    "masks": [
        "id": "Jaipur"
    ],
    "om_points": "Outcome",
    "parameters": [
        "id": "Jaipur"
    ]
}

 To print the JSON data I wrote this:

import json
from pprint import pprint

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

pprint(data)

but I faced an exception raised by the program: 

Traceback (most recent call last):
  File "<pyshell#1>", line 5, in <module>
    data = json.load(f)
  File "/usr/lib/python3.5/json/__init__.py", line 319, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.5/json/decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.5/json/decoder.py", line 355, in raw_decode
    obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting ',' delimiter: line 13 column 13 (char 213)

I want to parse the JSON and extract the values, How can I do it? 

2 Answers

0 votes
by (2k points)
edited by

The data you are using is not valid JSON format, You should use { } instead [ ] :

  • [ ] is for JSON arrays, and it's used for list in Python.

  • whereas { } is for for JSON objects, and it's used for dict in Python.

This is what you can use:

 {

    "maps": [
        {
            "id": "AT",
            "iscategorical": "0"
        },
        {
            "id": "AT",
            "iscategorical": "0"
        }
    ],
    "masks": {
        "id": "Jaipur"
    },
    "om_points": "output",
    "parameters": {
        "id": "Jaipur"
    }
}

 so you can use this code:

import json
from pprint import pprint

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

pprint(data)

 Using this data you can also find values like:

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

 Try these codes and if you have any doubts you can ask them in comments.

0 votes
by (107k points)

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

}

And your Python code should be as follows:

import json

from pprint import pprint

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

    data = json.load(data_file)

pprint(data)

You can use the following video tutorials to clear all your doubts:-

Related questions

+10 votes
2 answers
asked May 30, 2019 in Java by tommas (1k points)
0 votes
1 answer
asked Oct 27, 2019 in Java by Shubham (3.9k points)
0 votes
1 answer
asked Jul 3, 2019 in BI by Vaibhav Ameta (17.6k points)
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...