Parse a array of string objects

Based on the JSON data format below, how can we parse it where in I only wanted to get certain key for example I just wanted to get name and priority

[  
   "{'id': 12, 'category_name': 'BIR', 'priority': 1, 'category': 12, 'name': 'BIR FORMS'}",
   "{'id': 14, 'category_name': 'Contribution', 'priority': 0, 'category': 13, 'name': 'Pag-Ibig'}",
   "{'id': 13, 'category_name': 'Contribution', 'priority': 0, 'category': 13, 'name': 'SSS'}"
]

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

If you have no other quotes inside your data, you could replace single quotes ' with double quotes " to get a JSON compliant string.

Then parse the string, get the wanted properties and map new objects.

var strings = [  
        "{'id': 12, 'category_name': 'BIR', 'priority': 1, 'category': 12, 'name': 'BIR FORMS'}",
        "{'id': 14, 'category_name': 'Contribution', 'priority': 0, 'category': 13, 'name': 'Pag-Ibig'}",
        "{'id': 13, 'category_name': 'Contribution', 'priority': 0, 'category': 13, 'name': 'SSS'}"
    ],
    data = strings.map(s => JSON.parse(s.replace(/'/g, '"'))),
    selected = data.map(({ name, priority }) => ({ name, priority }));

console.log(selected);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Solution 2

Let’s assume that you have valid json data. You can do the following example:

const json = `[
   {"priority": 1, "name": "BIR FORMS"},
   {"priority": 0, "name": "Pag-Ibig"},
   {"priority": 0, "name": "SSS"}
]`;
const parsedJson = JSON.parse(json);

console.log(`${parsedJson[0].name}, ${parsedJson[0].priority}`);

Solution 3

try to map the data as bellow,

 let data=[
"{'id': 12, 'category_name': 'BIR', 'priority': 1, 'category': 12, 'name': 
'BIR FORMS'}", "{'id': 14, 'category_name': 'Contribution', 'priority': 0, 
'category': 13, 'name': 'Pag-Ibig'}", "{'id': 13, 'category_name': 
'Contribution', 'priority': 0, 'category': 13, 'name': 'SSS'}" ];
let mapping= data.map((tmp)=>{
   tmp=JSON.parse(tmp)
   return {name:tmp.name,priority:tmp.priority}
})

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply