How to parse JSON file with multiple objects - python

I am trying to parse a JSON file which is containing multiple JSON objects. Here is my code:
{
"obj1": {
"type": "object",
"permission": "r",
"obj2": {
"type": "param",
"permission": "r/w"
},
"obj3": {
"type": "param",
"permission": "r"
},
"obj4": {
"type": "object",
"permission": "r",
"obj5": {
"type": "param",
"permission": "r/w"
},
"obj6": {
"type": "param",
"permission": "r"
},
"obj7": {
"type": "object",
"permission": "r",
"obj8": {
"type": "param",
"permission": "r/w"
},
"obj9": {
"type": "param",
"permission": "r"
}
}
}
}
}
I had tried single object parsing response in JSON, that I able to fetch. But I don't not know how to parse the JSON object with Multiple nodes.
For each JSON obejct , I don't also know its name (obj1, obj2, ..)
I want in output as result:
obj1: has 2 param and 1 object
obj2: has 2 param and 1 object
obj3: has 2 param
Is there any way with python to parse JSON file with multiple objects?

try this:
op = json.loads(json_string)
for i,(key,value) in enumerate(op.items()):
objects = 0
params = len(value)
if isinstance(value,dict):
for k,v in value.items():
if isinstance(v,dict):
objects +=1
print("Object {i} has {params} params and {objects} objects".format(i=i+1,params=params-objects,objects=obj

Related

Combining multiple json schemas into a single json file with nested objects added to each endpoint

Hi I am currently trying to create a single json schema file from a few json schema files. I am looping through a list of jsons loaded, and output a single json with merged children objects.
Below is an example of an object that is present in both
object_in_first_list =
{
"path": "foo",
"name": "bar",
"schema": {
"name": "something",
"children": {
"child1": {
"name": "child1"
},
"child2": {
"name": "child2"
}
}
}
}
object_in_second_list =
{
"path": "foo",
"name": "bar",
"schema": {
"name": "something",
"children": {
"child2": {
"name": "child2"
},
"child3": {
"name": "child3"
}
}
}
}
These json objects are in a list that I am iterating over to create a unified JSON where the above objects will be merged and the output will be something like
{
"path": "foo",
"name": "bar",
"schema": {
"name": "something",
"children": {
"child1": {
"name": "child1"
},
"child2": {
"name": "child2"
},
"child3": {
"name": "child3"
}
}
}
}
I am currently iterating through the list using the two top level keys (path, name), putting them in a list(keywords), and then iterating over to add the endpoints to the new list(json).
for jsons in json_list:
for obj in jsons:
keyword = {
"path": obj["schema"]["path"],
"name": obj["schema"]["name"],
}
# If keyword does not exist in the list add to non_duplicate
if keyword not in keywords:
keywords.append(keyword)
updated_list.append(obj)
else:
# If Keyword matches

Validation Json Schema

I am trying to validate the json for required fields using python. I am doing it manually like iterating through the json reading it. Howerver i am looking for more of library / generic solution to handle all scenarios.
For example I want to check in a list, if a particular attribute is available in all the list items.
Here is the sample json which I am trying to validate.
{
"service": {
"refNumber": "abc",
"item": [{
"itemnumber": "1",
"itemloc": "uk"
}, {
"itemnumber": "2",
"itemloc": "us"
}]
}
}
I want to validate if I have refNumber and itemnumber in all the list items.
A JSON Schema is a way to define the structure of JSON.
There are some accompanying python packages which can use a JSON schema to validate JSON (jsonschema).
The JSON Schema for your example would look approximately like this:
{
"type": "object",
"properties": {
"service": {
"type": "object",
"properties": {
"refNumber": {
"type": "string"
},
"item": {
"type": "array",
"items": {
"type": "object",
"properties": {
"itemnumber": {
"type": "string"
},
"itemloc": {
"type": "string"
}
}
}
}
}
}
}
}
i.e., an object containing service, which itself contains a refNumber and a list of items.
Since i dont have enough rep to add a comment i will post this answer.
First i have to say i dont program with python.
According to my google search, you have a jsonschema module available for Python.
from jsonschema import validate
schema = {
"type": "object",
"properties": {
"service": {"object": {
"refNumber": {"type" : "string"},
"item: {"array": []}
},
"required": ["refNumber"]
},
},
}
validate(instance=yourJSON, schema=yourValidationSchema)
This example is not tested, but you can get some idea,
Link to jsonschema docs

Python JSON schema validation for array of objects

I am trying to validate a JSON file using the schema listed below, I can enter any additional fields, I don't understand, what I am doing wrong and why please?
Sample JSON Data
{
"npcs":
[
{
"id": 0,
"name": "Pilot Alpha",
"isNPC": true,
"race": "1e",
"testNotValid": false
},
{
"id": 1,
"name": "Pilot Beta",
"isNPC": true,
"race": 1
}
]
}
JSON Schema
I have set "required" and "additionalProperties" so I thought the validation would fail....
FileSchema = {
"definitions":
{
"NpcEntry":
{
"properties":
{
"id": { "type": "integer" },
"name": { "type" : "string" },
"isNPC": { "type": "boolean" },
"race": { "type" : "integer" }
},
"required": [ "id", "name", "isNPC", "race" ],
"additionalProperties": False
}
},
"type": "object",
"required": [ "npcs" ],
"additionalProperties": False,
"properties":
{
"npcs":
{
"type": "array",
"npcs": { "$ref": "#/definitions/NpcEntry" }
}
}
}
The JSON file and schema are processed using the jsonschema package for Python, (I am using python 3.7 on a Mac).
The method I use to read and validate is below, I have removed a lot of the general validation to make the code as short and usable as possible:
import json
import jsonschema
def _ReadJsonfile(self, filename, schemaSystem, fileType):
with open(filename) as fileHandle:
fileContents = fileHandle.read()
jsonData = json.loads(fileContents)
try:
jsonschema.validate(instance=jsonData, schema=schemaSystem)
except jsonschema.exceptions.ValidationError as ex:
print(f"JSON schema validation failed for file '{filename}'")
return None
return jsonData
at: "npcs": { "$ref": "#/definitions/NpcEntry" }
change "npcs" to "items". npcs is not a valid keyword so it is ignored. The only validation that is happening is at the top level, verifying that the data is an object and that the one property is an array.

Python: turn JSON object to JSON array

I have the following dictionary in python which I'm saving into a file:
d2 = {
"CHARACTER": {
"IDENTITY": {
"FORM": {
"id": "BK1",
"type": "MAGE",
"role": "DARK"
}
},
"USER": {
"owner": {
"id": "SABBATH13"
},
"level": "16"
}
}
}
jsonfile = open('d2.json', 'w')
jsonfile.write(simplejson.dumps(d2, indent=4))
jsonfile.close()
However, I'm told this is a JSON object, which I need to turn into a JSON array of the form:
[{
"CHARACTER": {
"IDENTITY": {
"FORM": {
"id": "BK1",
"type": "MAGE",
"role": "DARK"
}
},
"USER": {
"owner": {
"id": "SABBATH13"
},
"level": "16"
}
}
}]
Which is essentially adding square brackets at the beginning and end.
What is the proper way to do this? Should I convert to string and add brackets, then convert back? Sorry, total JSON newbie here.
You're thinking at the wrong level of abstraction. It's not about the brackets, it's about that you have a data structure which is an object, when what you apparently need is a list/array of objects (even if there's just one object in the list). So:
d2 = [d2]
Now dumps this and you get what you need.

decoding json string in python

I have the following JSON string (from wikipedia http://en.wikipedia.org/wiki/JSON)
{
"name":"Product",
"properties":
{
"id":
{
"type":"number",
"description":"Product identifier",
"required":true
},
"name":
{
"type":"string",
"description":"Name of the product",
"required":true
},
"price":
{
"type":"number",
"minimum":0,
"required":true
},
"tags":
{
"type":"array",
"items":
{
"type":"string"
}
},
"stock":
{
"type":"object",
"properties":
{
"warehouse":
{
"type":"number"
},
"retail":
{
"type":"number"
}
}
}
}
}
I am trying to decode this string using Python json library. I would like to access the node
properties - > stock - > properties - > warehouse.
I understand that json.loads() function stores the json string as a dictionary. But in this case properties is my key and everything under that are values. How do I access the above node.
import json
jsonText=""
file = open("c:/dir/jsondec.json")
for line in file.xreadlines():
jsonText+=line
data = json.loads(jsonText)
for k,v in data.items():
print k // shows name and properties
file.close();
Thanks
You can load json straight from the file like this:
f = open("c:/dir/jsondec.json")
data = json.load(f)
Based on your input string, data is now a dictionary that contains other dictionaries. You can just navigate up the dictionaries like so:
node = data['properties']['stock']['properties']['warehouse']
print str(node)

Categories

Resources