How to select and print values ​from json file

925 Views Asked by At

I have this json file. How do I view items with version "A" only? Thank you very much.

[
    {
      "id": 1,
      "version": "A",
      "description": "description 01",
      "title": "title 01"
    },
    {
      "id": 2,
      "version": "B",
      "description": "description 02",
      "title": "title 02"
    },
    {
      "id": 3,
      "version": "A",
      "description": "description 03",
      "title": "title 03"
    }
]

I know how to write all values ​​but how to write only "A", I don't know.

3

There are 3 best solutions below

0
Alcadur On

You can use filter method

const items = [
    {
      "id": 1,
      "version": "A",
      "description": "description 01",
      "title": "title 01"
    },
    {
      "id": 2,
      "version": "B",
      "description": "description 02",
      "title": "title 02"
    },
    {
      "id": 3,
      "version": "A",
      "description": "description 03",
      "title": "title 03"
    }
];

const versionAItems = items.filter( item => item.version === 'A' )
console.log(versionAItems)

0
Mr Khan On

If you want to just find items that matches the key (Eg. version), you can use find method like this:

let obj = 
[
    {
      "id": 1,
      "version": "A",
      "description": "description 01",
      "title": "title 01"
    },
    {
      "id": 2,
      "version": "B",
      "description": "description 02",
      "title": "title 02"
    },
    {
      "id": 3,
      "version": "A",
      "description": "description 03",
      "title": "title 03"
    }
];
let search =  "A"; //====> item to be searhed
let result = obj.find((item)=> item.version === search); // ===> Returns the value that satisfies the condition
console.log(result);

2
Adriano Campos On

Parsing JSON in QML is no different than parsing JSON in Javascript, because QML provides an environment based on ECMAScript with some modifications especially for QML.

So you can use the in-built JSON.parse() function like this:

var obj = '[
                {
                  "id": 1,
                  "version": "A",
                  "description": "description 01",
                  "title": "title 01"
                },
                {
                  "id": 2,
                  "version": "B",
                  "description": "description 02",
                  "title": "title 02"
                },
                {
                  "id": 3,
                  "version": "A",
                  "description": "description 03",
                  "title": "title 03"
                }
          ]'

var jsonData = JSON.parse(obj);

for (var i = 0; i < jsonData.length; i++) {
    console.log("Parse object i= " + i);
    if(jsonData[i].version === "B"){
        console.log(jsonData[i].id)
        console.log(jsonData[i].version)
        console.log(jsonData[i].description)
        console.log(jsonData[i].title)
    }
}