Json to tags directly using script console but not really working as intended

Hey Forum, I am back with another question

I have a nested Json and i am trying to form tags and folder structure from it directly but its not working for the nested part have no idea why

import json
import re
import time
 
# Sample JSON data
json_data = '''{
  "valve": {
    "id": "VALV12345",
    "type": "Ball Valve",
    "size_in_inches": 2,
    "material": "Stainless Steel",
    "pressure_rating_psi": 600,
    "connection_type": "Flanged",
    "actuation_type": "Manual",
    "manufacturer": "FlowTech Industries",
    "model_number": "FT-BV600-2SS",
    "installation_date": "2023-08-15",
    "last_maintenance_date": "2025-06-10",
    "status": "Operational",
    "location": {
      "plant": "Chennai Plant 3",
      "section": "Cooling Line A",
      "coordinates": {
        "latitude": 13.0827,
        "longitude": 80.2707
      }
    },
    "notes": "No issues reported during last inspection."
  }
}'''
 
# Parse JSON
data = json.loads(json_data)
valve_data = data["valve"]
valve_id = valve_data["id"]
base_path = "[default]Utkarsh_Valves/" + valve_id
 
# Detect datatype
def detect_datatype(value):
    if isinstance(value, bool):
        return "Boolean"
    elif isinstance(value, int):
        return "Int4"
    elif isinstance(value, float):
        return "Float8"
    elif isinstance(value, str):
        if re.match(r"\d{4}-\d{2}-\d{2}", value):
            return "Date"
        else:
            return "String"
    else:
        return "String"
 
# Recursive tag builder
def build_tags(data_dict):
    tags = []
    for key, value in data_dict.items():
        if isinstance(value, dict):
            tags.append({
                "name": key,
                "type": "Folder",
                "tags": build_tags(value)
            })
        else:
            tags.append({
                "name": key,
                "type": "Memory",
                "datatype": detect_datatype(value),
                "value": value
            })
    return tags
 
# ⛔ Step 1: Delete base path fully
if system.tag.exists(base_path):
    system.tag.deleteTags([base_path])
    time.sleep(0.5)  # Optional wait to allow deletion to finish
 
# ✅ Step 2: Build new tag structure excluding 'id'
tag_structure = build_tags({k: v for k, v in valve_data.items() if k != "id"})
 
# ✅ Step 3: Create the new tag structure
system.tag.configure(base_path, tag_structure, overwrite=True)

You can't use type for a folder.

Change "type": "Folder" to "tagType": "Folder"

References:

1 Like

My GPTdar is beeping so hard at this code !

Here's the structure you want:

{
	'name': key,
	'dataType': detect_datatype(value),
	'tagType': "AtomicTag",
	'valueSource': "memory",
}

{
	'name': key,
	'tagType': "Folder",
	'tags': build_tags(value)
}

Also note that:

  • the dataType for dates is DateTime, not Date.
  • system.tag.configure doesn't take an overwrite parameter. It takes collisionPolicy, which can have a value of "o" for overwrite.
  • You should be using system.util.jsonEncode and system.util.jsonDecode instead of importing json.
  • And why are you creating a json string, to then parse it ? Just make a dict !
  • I really doubt the sleep is justified.

Here's the code you need. But you should really, REALLY read the doc instead of blindly trusting an AI.

import re
 
data = {
	"valve": {
		"id": "VALV12345",
		"type": "Ball Valve",
		"size_in_inches": 2,
		"material": "Stainless Steel",
		"pressure_rating_psi": 600,
		"connection_type": "Flanged",
		"actuation_type": "Manual",
		"manufacturer": "FlowTech Industries",
		"model_number": "FT-BV600-2SS",
		"installation_date": "2023-08-15",
		"last_maintenance_date": "2025-06-10",
		"status": "Operational",
		"location": {
			"plant": "Chennai Plant 3",
			"section": "Cooling Line A",
			"coordinates": {
				"latitude": 13.0827,
				"longitude": 80.2707
			}
		},
		"notes": "No issues reported during last inspection."
	}
}
 
valve_data = data["valve"]
valve_id = valve_data["id"]
base_path = "[default]Utkarsh_Valves/" + valve_id
 
# Detect datatype
def detect_datatype(value):
	if isinstance(value, bool):
		return "Boolean"
	elif isinstance(value, int):
		return "Int4"
	elif isinstance(value, float):
		return "Float8"
	elif isinstance(value, str):
		if re.match(r"\d{4}-\d{2}-\d{2}", value):
			return "DateTime"
		else:
			return "String"
	else:
		return "String"
 
# Recursive tag builder
def build_tags(data_dict):
	tags = []
	for key, value in data_dict.items():
		if isinstance(value, dict):
			tags.append({
				"name": key,
				"tagType": "Folder",
				"tags": build_tags(value)
			})
		else:
			tags.append({
				"name": key,
				"tagType": "AtomicTag",
				"dataType": detect_datatype(value),
				"valueSource": "memory",
				"value": value
			})
	return tags
 
if system.tag.exists(base_path):
	system.tag.deleteTags([base_path])
 
tag_structure = build_tags({k: v for k, v in valve_data.items() if k != "id"})

system.tag.configure(base_path, tag_structure, "o")
6 Likes

Thank you for your time and guidance will keep that in mind moving forward regarding that can I get the doc link for reference

Link to system scripting functions:

Link to General Manual