You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 9中如何为动态响应内容添加行号显示

Alright, let's figure out how to add those clean, example-style line numbers to your JSON, XML, or plain string response bodies—since you already have the responseBody parsed, half the battle is won! The core idea is to split your formatted content into individual lines, then prepend a sequential number to each line (with optional styling to make it look polished).

1. For JSON Responses (Already Parsed)

Since you’ve already parsed the JSON object, first re-serialize it into a nicely formatted, indented string. Then split it into lines and add line numbers. Here’s a JavaScript example for frontend rendering:

// Assume you have the parsed responseBody.menu object
const formattedJson = JSON.stringify(responseBody.menu, null, 2); // 2 spaces for indentation
const lines = formattedJson.split('\n');

// Option 1: Plain text with line numbers
const numberedJsonText = lines.map((line, idx) => `${idx + 1}. ${line}`).join('\n');

// Option 2: Styled HTML (for better visual separation)
const numberedJsonHtml = lines.map(line => 
  `<span class="line-number"></span>${line}`
).join('\n');

// Render to the DOM (use <pre> to preserve whitespace)
document.getElementById('json-output').innerHTML = `<pre>${numberedJsonHtml}</pre>`;

Add this CSS to style the line numbers like a proper code example:

pre {
  counter-reset: line-counter;
  padding-left: 1.5em;
}
.line-number {
  display: inline-block;
  width: 3em;
  text-align: right;
  color: #888;
  margin-left: -3em;
  counter-increment: line-counter;
}
.line-number::before {
  content: counter(line-counter);
}

2. For XML Responses

First, you’ll need to format the raw XML string into human-readable, line-broken text. Use browser-native APIs or a simple formatting function, then add line numbers the same way as JSON:

function formatXml(rawXml) {
  const parser = new DOMParser();
  const xmlDoc = parser.parseFromString(rawXml, 'application/xml');
  const serializer = new XMLSerializer();
  // Basic formatting (adjust based on your needs)
  let formattedXml = serializer.serializeToString(xmlDoc);
  formattedXml = formattedXml.replace(/></g, '>\n<').replace(/^\s*\n/g, '');
  return formattedXml;
}

// Process the XML responseBody
const formattedXml = formatXml(responseBody);
const lines = formattedXml.split('\n');
const numberedXml = lines.map(line => 
  `<span class="line-number"></span>${line}`
).join('\n');

// Render with the same CSS as above
document.getElementById('xml-output').innerHTML = `<pre>${numberedXml}</pre>`;

3. For Plain String Responses

This is the simplest case—just split the string by newlines (or split into chunks if it’s a single line) and prepend line numbers:

const rawString = responseBody;
const lines = rawString.split('\n');
// Handle single-line strings by wrapping into one line
const numberedString = lines.map((line, idx) => `${idx + 1}. ${line}`).join('\n');

// If you want to split long single lines into chunks (e.g., 80 chars per line)
const splitLongLines = (str, maxLength) => {
  return str.match(new RegExp(`.{1,${maxLength}}`, 'g')) || [str];
};
const chunkedLines = splitLongLines(rawString, 80);
const numberedChunkedString = chunkedLines.map((line, idx) => `${idx + 1}. ${line}`).join('\n');

Backend Example (Python)

If you’re generating the numbered output on the server side, the logic is identical—format the content, split into lines, and add numbers:

import json

def add_line_numbers(content):
    lines = content.split('\n')
    return '\n'.join([f"{i+1}. {line}" for i, line in enumerate(lines)])

# Process JSON
formatted_json = json.dumps(response_body['menu'], indent=2)
numbered_json = add_line_numbers(formatted_json)

# Process XML (use xml.dom.minidom for formatting)
import xml.dom.minidom
raw_xml = response_body
dom = xml.dom.minidom.parseString(raw_xml)
formatted_xml = dom.toprettyxml(indent='  ')
numbered_xml = add_line_numbers(formatted_xml)

Key Notes

  • Empty Lines: Adjust the mapping logic if you don’t want line numbers for empty lines (add a condition like if line.trim()).
  • Line Number Starting Point: Change idx + 1 to idx if you want zero-indexed lines.
  • Styling: Tweak the CSS to match your app’s design—you can make line numbers fixed-width, grayed out, or even add a vertical divider.

内容的提问来源于stack exchange,提问作者dev_101

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 14:17:30