json转obj

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>json转obj</title>
  <meta name="renderer" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
  <style type="text/css">
  
  </style>
</head>
<body>

<div>
    
</div>

<script src="http://www.h5al.cn/js/jquery-1.11.3.min.js"></script>
<script>
function convertToUnquotedKeys(obj) {
    if (obj === null || typeof obj !== 'object') return obj;
    if (Array.isArray(obj)) return obj.map(item => convertToUnquotedKeys(item));
    const result = {};
    for (const [key, value] of Object.entries(obj)) {
        result[key] = convertToUnquotedKeys(value);
    }
    return result;
}

function stringifyWithoutKeyQuotes(obj, indent = 2, level = 0) {
    const spaces = ' '.repeat(level * indent);
    const nextSpaces = ' '.repeat((level + 1) * indent);
    
    if (obj === null) return 'null';
    if (typeof obj !== 'object') {
        if (typeof obj === 'string') return `"${obj.replace(/"/g, '\\"')}"`;
        return String(obj);
    }
    if (Array.isArray(obj)) {
        const items = obj.map(item => stringifyWithoutKeyQuotes(item, indent, level + 1));
        return `[\n${nextSpaces}${items.join(`,\n${nextSpaces}`)}\n${spaces}]`;
    }
    const entries = Object.entries(obj).map(([key, value]) => {
        return `${nextSpaces}${key}: ${stringifyWithoutKeyQuotes(value, indent, level + 1)}`;
    });
    return `{\n${entries.join(',\n')}\n${spaces}}`;
}

// 使用方法 - 假设你的数据在变量 data 中
// const converted = convertToUnquotedKeys(yourData);
// const output = stringifyWithoutKeyQuotes(converted);
// console.log(output);
// 复制结果: copy(output)


let jsonData = [];//粘贴JSON
const converted = convertToUnquotedKeys(jsonData);
const output = stringifyWithoutKeyQuotes(converted);
console.log(output);
</script>

</body>
</html>

 

posted @ 2026-09-29 09:44  峪野  阅读(6)  评论(0)    收藏  举报