Convert IfcOpenShell objects / iterables into JSON-safe primitives.
(x: Any)
| 36 | |
| 37 | |
| 38 | def _jsonify(x: Any) -> Any: |
| 39 | """Convert IfcOpenShell objects / iterables into JSON-safe primitives.""" |
| 40 | if x is None or isinstance(x, (str, int, float, bool)): |
| 41 | return x |
| 42 | |
| 43 | # numpy arrays (and any array-like with tolist) |
| 44 | if hasattr(x, "tolist"): |
| 45 | return x.tolist() |
| 46 | |
| 47 | # IfcOpenShell entity instances: normalize |
| 48 | if isinstance(x, ifcopenshell.entity_instance): |
| 49 | return { |
| 50 | "id": int(x.id()), |
| 51 | "type": x.is_a(), |
| 52 | "repr": str(x), |
| 53 | "name": getattr(x, "Name", None), |
| 54 | } |
| 55 | |
| 56 | if isinstance(x, dict): |
| 57 | return {str(k): _jsonify(v) for k, v in x.items()} |
| 58 | |
| 59 | if isinstance(x, (list, tuple, set)): |
| 60 | return [_jsonify(v) for v in x] |
| 61 | |
| 62 | # Try JSON as-is, else fallback to string |
| 63 | try: |
| 64 | json.dumps(x) |
| 65 | return x |
| 66 | except Exception: |
| 67 | return str(x) |
| 68 | |
| 69 | |
| 70 | # --------------------------------------------------------------------------- |