简体   繁体   中英

Convert string array of key-value pair to array of objects javascript

The response I get from API is like this:

"1012": "[{oId=151, oName=store city}, {oId=247, oName=customer city}]"

I want to convert the output's value to array of objects like below:

[
    {
      "oId": 151,
      "oName": "store city"
    },
    {
      "oId": 247,
      "oName": "customer city"
    }
]

Can you please help me in how to do this in JavaScript?

Since the response is not a JSON and we don't exactly know the specification of the API response (is there a spec for this kind of return?), you can try to parse it with a dirty hack .

const str = "[{oId=151, oName=store city}, {oId=247, oName=customer city}]";

const result = JSON.parse(
  str.replaceAll(", ", ",")
     .replace(/([^,{]+)?=([^,}]+)?/gi, `"$1":"$2"`) // Sorry.
);

Result will return:

[
    {
      "oId": 151,
      "oName": "store city"
    },
    {
      "oId": 247,
      "oName": "customer city"
    }
]

Please note that it will fix your actual issue, still:

  • It will not work in all cases (if there is coma in string or double quote somewhere.
  • I strongly advise that you contact the API designer since they created a super exotic format that does not scale at all.

You will need a custom parser for this since the it is a string and it does not conform to JSON format. Following snippet might help you:

 const data = { "1012": "[{oId=151, oName=store city}, {oId=247, oName=customer city}]" } function parseCustom(str) { const regex = /(\w+)=(.*?)([,}])/gm; const subst = `"$1":"$2"$3`; return str.replace(regex, subst); } const parsedData = JSON.parse(parseCustom(data["1012"])) console.log(parsedData)

The solution above uses regular expression to replace = with : and does some other basic replacements to make it look like JSON. The solution above will still treat the numbers as string as its inside quotes. The snippet below loops through the array and converts if any valid number is present in values of the object. Run the snippets to see if it matches your requirements.

 const data = { "1012": "[{oId=151, oName=store city}, {oId=247, oName=customer city}]" } function parseCustom(str) { const regex = /(\w+)=(.*?)([,}])/gm; const subst = `"$1":"$2"$3`; return str.replace(regex, subst); } const parsedData = JSON.parse(parseCustom(data["1012"])) // parse values as numbers if its valid Number // assumes that the parsedData is an Array const parsedDataNumber = parsedData.map(d => { for (let key in d) { if (Number(d[key])) { d[key] = Number(d[key]) } } return d }) console.log("Number parsed") console.log(parsedDataNumber)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM