I'm writing some code to infer a json schema def inferschema(data): if isinstance(data,…
- User
I'm writing some code to infer a json schema
def infer_schema(data): if isinstance(data, dict): schema = {} for key, value in data.items(): schema[key] = infer_schema(value) return schema elif isinstance(data, list): if data: # check if the list is not empty child_schemas = [infer_schema(x) for x in data] union = {} for child_schemas in child_schemas: union.update(child_schemas) return [union] else: return [] else: return type(data).name
Problem is when i see the list: the update is not recursive i.e. If i see {'a': {'b': 3}}, and {'a': {'b': 3, 'c': 4}}, I want to update to the schema {'a': {'b': 'int', 'c': 'int'}}
Assistant
The issue is that the
uniondictionary is being overwritten in each iteration of the loop, instead of being recursively updated.To fix this, you can use a recursive function that updates the schema for each child schema, and then combines the results. Here's an updated implementation:
python
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.