如何在javascript/typescript中将此字符串转换为JSON对象?

fd3cxomn  于 2022-12-30  发布在  Java
关注(0)|答案(2)|浏览(301)

我一直在尝试将这段字符串转换为正确的JSON对象,经过多次字符串操作和尝试,甚至在使用JSON。parse和stringify函数也帮不了我。有人能帮我将这段字符串转换为正确的JSON对象吗?

"{\n  status: 'success',\n  message: 'The user is able to enter data in search bar.'\n}\n{ status: 'success', message: 'Number of cities with letter p are 4.' }\n{\n  status: 'success',\n  message: 'Success messagecity addedappears in green'\n}\n{\n  status: 'success',\n  message: 'The city added is visible under Cities header.'\n}\n"

我试过使用JSON.parse和stringify函数,也试过使用replaceAll、split(),但都无济于事。

ct2axkht

ct2axkht1#

1.字符串中的每个对象都缺少一些逗号,所以首先要添加这些逗号。
1.字符串是一堆分离的对象,所以在将其转换为json之前,让我们将它们混合到一个数组中。

const jsObjecStringWithoutN = document.querySelector('#jsObjecStringWithoutN');
const jsObjecStringAddingCommas = document.querySelector('#jsObjecStringAddingCommas');
const JSONObject = document.querySelector('#JSONObject');

const javascriptObject = "{\n  status: 'success',\n  message: 'The user is able to enter data in search bar.'\n}\n{ status: 'success', message: 'Number of cities with letter p are 4.' }\n{\n  status: 'success',\n  message: 'Success messagecity addedappears in green'\n}\n{\n  status: 'success',\n  message: 'The city added is visible under Cities header.'\n}\n";

// replace the \\n character
const replaceEnter = javascriptObject.replaceAll('\n', '');
jsObjecStringWithoutN.innerText = replaceEnter;

// add commas at the end of each separated object
const addingCommas = replaceEnter.replaceAll('}{', '},{');
jsObjecStringAddingCommas.innerText = addingCommas;

//replace single quotes to double quotes
const replacingQuotes = addingCommas.replaceAll("\'",'"');

let jsonString = "["+replacingQuotes+"]";
// put double quotes in keys
const jsonObjectText = jsonString.replaceAll(/[a-zA-Z0-9]+:/ig, (key)=>{
  const formattedKey = key.replace(':','');
  return '"'+formattedKey+'":';
});
const jsonObject = JSON.parse(jsonObjectText);
JSONObject.innerText = JSON.stringify(jsonObject);
code{
  background: #ececec;
}
<h2>Javascript Object</h1>

<code id="jsObjectString">{\n  status: 'success',\n  message: 'The user is able to enter data in search bar.'\n}\n{ status: 'success', message: 'Number of cities with letter p are 4.' }\n{\n  status: 'success',\n  message: 'Success messagecity addedappears in green'\n}\n{\n  status: 'success',\n  message: 'The city added is visible under Cities header.'\n}\n"</code>

<h3>First step, delete "/n"</h3>
<code id="jsObjecStringWithoutN"></code>

<h3>Second step, adding commas</h3>
<code id="jsObjecStringAddingCommas"></code>

<h3>Third step, wrap it all up in one array of objects and convert it to JSON</h3>
<code id="JSONObject"></code>
t2a7ltrp

t2a7ltrp2#

const messageArray = str.replaceAll("\n","").replaceAll("}{","},{").replaceAll('status:', '"status":').replaceAll('message:', '"message":').replaceAll("'", '"').match(/{(.)*?}/g).map(i => JSON.parse(i))

但这是一种可怕的方式,最好是让这一耻辱的始作俑者有一个正常的看法。

相关问题