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

JavaScript将JSON字符串转为格式化JSON及回调脚本问题咨询

Hey James, let's break down your two technical questions with clear, actionable solutions:

1. Converting a JSON string to pretty-printed JSON in JavaScript

To turn a minified JSON string into a human-readable (pretty) format, JavaScript's built-in JSON.stringify() method is your best bet. It’s important to note that you first need to parse the string into a JavaScript object (to validate it’s valid JSON), then stringify it with indentation.

Example code:

const jsonString = '{"event":"success","method":"sale","request_id":"275936ad-83c0-4afd-88ff-6943c4ee2781"}';

try {
  // Parse the string to a JS object (validates the JSON at the same time)
  const jsonObject = JSON.parse(jsonString);
  // Stringify with 2 spaces of indentation for clean readability
  const prettyJson = JSON.stringify(jsonObject, null, 2);
  
  console.log(prettyJson);
  // You can also insert this into the DOM if needed:
  // document.getElementById('formatted-json').textContent = prettyJson;
} catch (error) {
  console.error("Invalid JSON input:", error.message);
}

Key tips:

  • Always wrap this logic in a try-catch block to handle invalid JSON gracefully (e.g., typos or malformed strings).
  • The third argument in JSON.stringify() (we used 2 here) sets the indentation spacing—use 4 if you prefer more room.
  • Skipping the JSON.parse step will just stringify the original string itself (adding extra quotes), which isn’t what you want.
2. Handling the auto-injected callback script and its JSON output

First, let’s unpack what that script does:

<script type="text/javascript"> function oncallback(e) { $('#message').html(e.data); } </script>

This defines a callback function oncallback that takes an event object e, then inserts the JSON string from e.data into the DOM element with ID message. This is a standard pattern for third-party services (like payment gateways) to send callback data to your frontend.

Practical ways to work with this data:

Option 1: Override the callback to capture data upfront

If you can intercept the script before it runs, override the oncallback function to save the data before it’s rendered to the DOM:

// Override the oncallback function before the third-party script loads
window.oncallback = function(e) {
  // Parse the JSON data immediately
  const callbackData = JSON.parse(e.data);
  console.log("Received callback data:", callbackData);
  
  // Optional: Keep rendering the data to #message if needed
  $('#message').html(e.data);
  
  // Add your custom logic here (e.g., send to your backend, update UI)
  if (callbackData.event === "success") {
    alert(`Payment approved! Authorization code: ${callbackData.authorization_code}`);
  }
};

Option 2: Extract data from the #message element

If you can’t modify the callback, you can read the data directly from the DOM once it’s been inserted. For reliability, use a MutationObserver instead of a timeout to detect when the element updates:

const messageElement = document.getElementById('message');

// Set up an observer to watch for changes to the element
const observer = new MutationObserver((mutations) => {
  mutations.forEach((mutation) => {
    if (mutation.type === 'childList' && messageElement.textContent.trim()) {
      try {
        const callbackData = JSON.parse(messageElement.textContent);
        console.log("Extracted callback data:", callbackData);
        observer.disconnect(); // Stop observing once we get the data
      } catch (error) {
        console.error("Failed to parse JSON from #message:", error.message);
      }
    }
  });
});

// Start observing the element for content changes
observer.observe(messageElement, { childList: true, subtree: true });

Option 3: Verify the script’s origin

Since you didn’t write this script, it’s almost certainly injected by a third-party service you’re integrating with (like a payment processor). Double-check your integration documentation to confirm this is expected behavior. If you’re unsure about its legitimacy, use your browser’s dev tools to inspect where the script is loaded from—only trust sources from verified, trusted domains.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:59:38