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

C#中按大小拆分JSON为完整元组并存入字符串数组

Solution to Split JSON into Valid Chunks with Complete Tuples

Got it, let's fix this properly. The problem with just splitting the raw string is that you risk breaking the JSON structure mid-tuple. Instead, we'll parse the JSON first, then build chunks by adding complete key-value pairs until each chunk's JSON string stays under your 165-character limit. This ensures every chunk is valid JSON with no broken tuples.

Here's a practical JavaScript implementation that does exactly this:

function splitJsonIntoValidChunks(jsonString, maxLength) {
  // Parse the original JSON into an object to work with individual tuples
  const data = JSON.parse(jsonString);
  const chunks = [];
  let currentChunk = {};

  for (const [key, value] of Object.entries(data)) {
    // Test if adding the current tuple keeps the chunk under the max length
    const testChunk = {...currentChunk, [key]: value};
    const testChunkStr = JSON.stringify(testChunk);

    if (testChunkStr.length <= maxLength) {
      // Safe to add this tuple to the current chunk
      currentChunk = testChunk;
    } else {
      // Finalize the current chunk and start a new one with this tuple
      chunks.push(JSON.stringify(currentChunk));
      currentChunk = {[key]: value};
    }
  }

  // Add the last remaining chunk if it's not empty
  if (Object.keys(currentChunk).length > 0) {
    chunks.push(JSON.stringify(currentChunk));
  }

  return chunks;
}

// Example usage tailored to your need (split into 2 chunks)
const originalJson = `{
  "user_id": "1234567890abcdefghijklmnopqrstuvwxyz",
  "username": "aparna123",
  "email": "aparna@example.com",
  "bio": "I work with JSON and need to split payloads into valid chunks without breaking tuples.",
  "location": "New York, NY",
  "joined_date": "2020-01-01",
  "preferences": {"notifications": true, "dark_mode": false},
  "recent_activity": ["logged_in", "viewed_profile"]
}`;

const maxLength = 165;
const result = splitJsonIntoValidChunks(originalJson, maxLength);

// Output the result
console.log("Split chunks:");
result.forEach((chunk, index) => {
  console.log(`Chunk ${index + 1} (length: ${chunk.length}):`);
  console.log(chunk);
});

How this works:

  1. Parse first: We convert the input JSON string into an object so we can handle each key-value pair (tuple) individually.
  2. Build chunks incrementally: For each tuple, we test if adding it to the current chunk keeps the JSON string under your 165-character limit.
  3. Split only when necessary: If adding a tuple would exceed the limit, we finalize the current chunk (convert back to JSON) and start a new chunk with that tuple.
  4. Cleanup: We add any remaining tuples in the last partial chunk to the result.

Edge case note:

If a single tuple's JSON string is longer than 165 characters, this function will create a chunk with just that tuple (even if it's over the limit). You can add extra logic to handle this (like truncating long values) if needed, but that depends on your specific use case.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 10:18:52