Why Can't Python Parse This Json Data

Why can't Python parse this JSON data?

Your data is not valid JSON format. You have [] when you should have {} for the "masks" and "parameters" elements:

  • [] are for JSON arrays, which are called list in Python
  • {} are for JSON objects, which are called dict in Python

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 f:
data = json.load(f)

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.

Can't parse this json file

@user9371654, there are 2 main problems associated with your JSON file and Python code.

  • The contents of result2.json is not properly formatted.

  • The parameters of print() function should be separated with , so replace all + used for concatenation with , ( If you still prefer , then uou will need to convert your list to string using str() to support concatenation).

Copy your JSON content of result2.json and format it at https://jsonformatter.curiousconcept.com.

Sample Image

result2.json

Sample Image

Note: Update your JSON file result2.json with the following content.

[  
{
"host":"host1.com",
"ip":"x.x.x.x",
"port":443,
"tlsVersions":[
"TLSv1_2"
],
"cipherSuite":{
"supported":[
"ECDHE-RSA-AES256-GCM-SHA384"
]
},
"x509ChainDepth":2,
"verifyCertResult":true,
"verifyHostResult":true,
"ocspStapled":true,
"verifyOcspResult":true,
"certificateChain":[
{
"version":3
},
{
"version":3
}
]
},
{
"host":"host2.com",
"ip":"y.y.y.y",
"port":443,
"tlsVersions":[
"TLSv1_2"
],
"cipherSuite":{
"supported":[
"ECDHE-RSA-AES256-GCM-SHA384"
]
},
"x509ChainDepth":2,
"verifyCertResult":true,
"verifyHostResult":true,
"ocspStapled":true,
"verifyOcspResult":true,
"certificateChain":[
{
"version":3
},
{
"version":3
}
]
}
]

Python Code

Finally try the below code:

import json 

with open('result2.json', 'r') as f:
distros_dict = json.load(f)

for distro in distros_dict:
print(distro['host'], "," , distro['tlsVersions'], '\n')

Output

host1.com , ['TLSv1_2']

host2.com , ['TLSv1_2']

python can't parse json string

json_data = ''.join(map(str, script.contents))
>>> json_data = json.dumps(json_data.strip(' \t\n\r'))
data = json.loads(json_data)

The marked line is the problem. json_data is currently a string encoding a dictionary, and when you call json.dumps, it will then be a string encoding a string encoding a dictionary, and your last line just undoes one instance. What is it that you're actually trying to do with the marked line?

python unable to parse JSON Data

in short, json.loads converts from a Json (thing, objcet, array, whatever) into a Python object - in this case, a Json Dictionary. When you print that, it will print as a itterative and therefore print with single quotes..

Effectively your code can be expanded:

some_dictionary = json.loads(a_string_which_is_a_json_object)
print(some_dictionary)

to make sure that you're printing json-safe, you would need to re-encode with json.dumps

Can't parse json file: json.decoder.JSONDecodeError: Extra data.

Your JSON data set is not valid , You can merge them into one array of objects.
For example :

[
{
"host": "a.com",
"ip": "1.2.2.3",
"port": 8
}, {
"host": "b.com",
"ip": "2.5.0.4",
"port": 3

}, {
"host": "c.com",
"ip": "9.17.6.7",
"port": 4
}
]

In JSON you can't have multiple objects of top-level but you can have array of objects and it is valid

You can see more JSON Data Set examples if you want in this link

  • If you want to know more about JSON arrays you can read in w3schools JSON tutorial

Python: Json.load gives list and can't parse data from it

You could use the ast module for this:

import ast

mydata = ["{\"Day\":\"Today\",\"Event\":\"1\", \"Date\":\"2019-03-20\"}"]
data = ast.literal_eval(mydata[0])
data
{'Day': 'Today', 'Event': '1', 'Date': '2019-03-20'}

data['Event']
'1'

Edit

Your original code does load the data into a list structure, but only contains a single string entry inside that list, despite proper json syntax. ast, like json, will parse that string entry into a python data structure, dict.

As it sits, when you try to index that list, it's not the same as calling a key in a dict, hence the slices cannot be str:

alist = [{'a':1, 'b':2, 'c':3}]
alist['a']
TypeError

# need to grab the dict entry from the list
adict = alist[0]
adict['a']
1

Can't parse Json text with unicode codes with Python 3.7

I think you need to use 'raw_unicode_escape'.

import json
with open("j.json", encoding='raw_unicode_escape') as f:
data = json.loads(f.read().encode('raw_unicode_escape').decode())
print(data[0])

OUT: {'timestamp': 1575826804, 'attachments': [], 'data': [{'post': 'This is a test line with character í and ó'}, {'update_timestamp': 1575826804}], 'title': 'My Name'}

Does this help?

I can't parse a json file with python

Once you read a file, its stream is at the end and cannot be read from anymore. Your code should work if you remove the print data_file.read() statement, or you .seek() back to the beginning of the file afterwards.

Python can't parse JSON with extra trailing comma

Another option is to parse it as YAML; YAML accepts valid JSON but also accepts all sorts of variations.

import yaml
s = '{ "key1": "value1", "key2": "value2", }'
yaml.load(s)


Related Topics



Leave a reply



Submit