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

如何修改数组并转换为JSON?ES6实现结果异常排查

Fixing Your Invalid JSON Conversion Issue

Hey there, let's sort out this JSON formatting problem you're facing. First, let's break down what's wrong with your current result:

{"Quotes:true","Flight Logs:true","Currency Records:true","FTD:true","Maintenance Tracker:true"}

This isn't valid JSON because:

  • Object keys must be wrapped in double quotes (e.g., "Quotes" instead of Quotes)
  • The key-value pairs are formatted as strings separated by commas, instead of proper key: value entries inside the object.

Correct ES6 Implementation

Assuming your original array looks like this (a list of the keys you want):

const originalArray = ["Quotes", "Flight Logs", "Currency Records", "FTD", "Maintenance Tracker"];

Here are two clean ES6 ways to convert it to valid JSON:

Method 1: Use Object.fromEntries()

This is the most concise approach for modern JavaScript environments:

// Convert array to an object where each key maps to true
const resultObj = Object.fromEntries(originalArray.map(item => [item, true]));
// Convert the object to valid JSON
const validJSON = JSON.stringify(resultObj, null, 2);

console.log(validJSON);

Method 2: Use Array.reduce()

If you need more control (or support slightly older environments), reduce works great too:

const resultObj = originalArray.reduce((acc, item) => {
  acc[item] = true;
  return acc;
}, {});

const validJSON = JSON.stringify(resultObj, null, 2);

console.log(validJSON);

What You'll Get

Both methods will output this valid, properly formatted JSON:

{
  "Quotes": true,
  "Flight Logs": true,
  "Currency Records": true,
  "FTD": true,
  "Maintenance Tracker": true
}

Why Your Original Approach Failed

It looks like you might have tried manually concatenating strings to build the JSON, which is error-prone. Always use JSON.stringify() on a properly structured JavaScript object—this ensures the output follows JSON syntax rules automatically.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 08:18:34