如何使用Angular 2判断字符串类型为XML、JSON或普通字符串
Great question! This is a common task when handling unstructured string inputs, and the approach boils down to attempting to parse the string against each format (JSON first, then XML) and falling back to plain text if neither works. Here's a practical, step-by-step implementation with code examples:
Step 1: Detect and Format JSON Objects
JSON has strict syntax, making it reliable to parse first. We’ll check if the string parses into an object or array (since you specified "JSON object", but arrays are also common valid JSON structures).
JavaScript Example
function isJson(str) { try { const parsed = JSON.parse(str); // Verify it's an object/array (not a primitive like a string or number) return typeof parsed === 'object' && parsed !== null; } catch (e) { return false; } } function formatJson(str) { return JSON.stringify(JSON.parse(str), null, 2); }
Python Example
import json def is_json(s): try: parsed = json.loads(s) return isinstance(parsed, (dict, list)) except ValueError: return False def format_json(s): return json.dumps(json.loads(s), indent=2)
Step 2: Detect and Format XML
XML detection is trickier due to its flexible syntax. We’ll start with a quick check for XML-specific patterns, then validate by parsing.
JavaScript Example
function isXml(str) { // Quick pre-check: does it start with an XML declaration or element tag? const trimmedStr = str.trim(); if (!trimmedStr.startsWith('<?xml') && !trimmedStr.startsWith('<')) { return false; } try { const parser = new DOMParser(); const xmlDoc = parser.parseFromString(str, 'text/xml'); // Check for parsing errors const parseError = xmlDoc.querySelector('parsererror'); return !parseError; } catch (e) { return false; } } function formatXml(str) { const parser = new DOMParser(); const xmlDoc = parser.parseFromString(str, 'text/xml'); // Custom pretty-print helper (works across most browsers) function prettyPrint(node, indent = '') { let result = `${indent}${node.nodeName}`; // Add attributes if present if (node.attributes.length > 0) { result += ' ' + Array.from(node.attributes) .map(attr => `${attr.name}="${attr.value}"`) .join(' '); } // Handle empty elements if (node.childNodes.length === 0) { return `${result}/>\n`; } result += '>\n'; indent += ' '; // Recursively process child nodes for (const child of node.childNodes) { if (child.nodeType === Node.ELEMENT_NODE) { result += prettyPrint(child, indent); } else if (child.nodeType === Node.TEXT_NODE && child.textContent.trim()) { result += `${indent}${child.textContent.trim()}\n`; } } indent = indent.slice(2); result += `${indent}</${node.nodeName}>\n`; return result; } return prettyPrint(xmlDoc.documentElement); }
Python Example
import xml.etree.ElementTree as ET from xml.dom import minidom def is_xml(s): trimmed_s = s.strip() if not (trimmed_s.startswith('<?xml') or trimmed_s.startswith('<')): return False try: ET.fromstring(s) return True except ET.ParseError: return False def format_xml(s): parsed = ET.fromstring(s) rough_string = ET.tostring(parsed, 'utf-8') reparsed = minidom.parseString(rough_string) return reparsed.toprettyxml(indent=" ")
Step 3: Detect Plain Strings
If the string fails both JSON and XML parsing checks, it’s a plain string. Return it as-is, or add basic formatting like line breaks if needed.
Full Combined Function
Putting it all together, here’s a function that detects the type and returns the formatted result:
JavaScript
function detectAndFormat(str) { if (isJson(str)) { return { type: 'JSON Object', formatted: formatJson(str) }; } else if (isXml(str)) { return { type: 'XML', formatted: formatXml(str) }; } else { return { type: 'Plain String', formatted: str }; } } // Usage examples: console.log(detectAndFormat('{"name": "Alice", "age": 30}')); console.log(detectAndFormat('<user><name>Bob</name><age>25</age></user>')); console.log(detectAndFormat('Hello, this is a plain string!'));
Python
def detect_and_format(s): if is_json(s): return {"type": "JSON Object", "formatted": format_json(s)} elif is_xml(s): return {"type": "XML", "formatted": format_xml(s)} else: return {"type": "Plain String", "formatted": s} // Usage examples: print(detect_and_format('{"name": "Alice", "age": 30}')) print(detect_and_format('<user><name>Bob</name><age>25</age></user>')) print(detect_and_format('Hello, this is a plain string!'))
Key Notes
- Order Matters: Always check JSON first—some XML strings might pass initial pattern checks, but strict JSON parsing will rule out false positives.
- Edge Cases: Invalid XML/JSON strings might pass the initial pattern check, so always follow up with actual parsing validation.
- JSON Primitives: If you want to include valid JSON primitives (like
"hello"or42) as JSON type, adjust theisJsonfunction to return true for any valid JSON, not just objects/arrays.
内容的提问来源于stack exchange,提问作者Lavanya Komarasamy

