簡體   English   中英

將字符串轉換為有效的 json

[英]converting string to a valid json

我需要使用 node.js 從 javascript 文件中提取一個對象。 我能夠讀取 javascript 文件,也能夠將需要轉換為對象的字符串切片。 這是我的代碼。

const AboutLocale = function() {
  return {
    person: {
      name: "zxczv",
      age: 25,
      gender: "male",
    },
    ar: true,
  };
};

我只想要這個文件中的 person 對象,我可以使用切片運算符來實現這一點。 現在它給了我一個看起來像這樣的字符串

  "{
    name: "man",
    age: 25,
    gender: "male",
  }"

我嘗試解析它,但它不是有效的 JSON。 我需要幫助將其轉換為有效對象。

你可以用一些正則表達式來做到這一點。 第一個用它們自己替換所有屬性名稱,但引用。 第二個刪除右括號前的所有逗號。 請注意,這是一個非常脆弱的解決方案,如果您向其拋出任何意外,則可能會中斷。 最好只運行文件,運行命令 AboutLocale,然后 JSON.stringify 將輸出轉換為有效的 JSON。

 const input = `{ name: "man", age: 25, gender: "male", }` const input2 = `{header:"Aboutjdkahsfjk34",productShortName:"OBDX123456",version:"Version",servicePack:"Service Pack",poweredByValue:"asag",copyright:"Copyright 2006-2020",build:"Build",name:"manav"}` const input3 = `{header:"Aboutjdka,hsfjk34",productShortName:"OBDX1,23456",version:"Version",servicePack:"Service Pack",poweredByValue:"asag",copyright:"Copyright 2006-2020",build:"Build",name:"manav"}` fixed = input.replace(/\\b(.*?):/g, "\\"$1\\":").replace(/,.*\\n.*}/gm, "}") fixed2 = input2.replace(/([,{])(.*?):/g, "$1\\"$2\\":") let fixed3 = "" let inAProperty = false input3.split("").forEach((e,i) => { if (e === "{") fixed3 += "{\\"" else if (e === ":") fixed3 += "\\":" else if (e === ",") fixed3 += inAProperty ? e : ",\\"" else if (e === "\\"") { inAProperty = !inAProperty fixed3 += e } else fixed3 += e }) console.log(fixed) console.log(JSON.parse(fixed)) console.log(fixed2) console.log(JSON.parse(fixed2)) console.log(fixed3) console.log(JSON.parse(fixed3))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM