-2

I have a JSON which contains directory structure and needs to convert to javascript object so that a map for key-value pair can be formed from it.

{
    "/Inbound/tmp/ARTIFACTDOWNLOAD_DIR": [
        {
            "filePath": "/Inbound/tmp/ARTIFACTDOWNLOAD_DIR",
            "fileName": "package_installation_logs.txt",
            "lastModifiedDate": "06-14-2019 09:34:43",
            "sizeofFile": "0 KB",
            "type": "File"
        }
    ],
    "/Inbound": [
        {
            "filePath": "/Inbound",
            "fileName": "osqueryd.INFO",
            "lastModifiedDate": "06-14-2019 09:23:26",
            "sizeofFile": "1 KB",
            "type": "File"
        },
        {
            "filePath": "/Inbound",
            "fileName": "tmp",
            "lastModifiedDate": "06-14-2019 10:51:55",
            "sizeofFile": "",
            "type": "Folder"
        }
    ]
}

Here key-value pairs in JSON contain different keys. So, how I can map key-value to javascript object using typescript

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
user3400625
  • 53
  • 1
  • 1
  • 4
  • possible duplicate of https://stackoverflow.com/questions/8294088/javascript-object-vs-json – AZ_ Jun 18 '19 at 08:59

2 Answers2

1

Simply use it like this

// your JSON - compressed
const json = '{"/Inbound/tmp/ARTIFACTDOWNLOAD_DIR":[{"filePath":"/Inbound/tmp/ARTIFACTDOWNLOAD_DIR","fileName":"package_installation_logs.txt","lastModifiedDate":"06-14-2019 09:34:43","sizeofFile":"0 KB","type":"File"}],"/Inbound":[{"filePath":"/Inbound","fileName":"osqueryd.INFO","lastModifiedDate":"06-14-2019 09:23:26","sizeofFile":"1 KB","type":"File"},{"filePath":"/Inbound","fileName":"tmp","lastModifiedDate":"06-14-2019 10:51:55","sizeofFile":"","type":"Folder"}]}'

const objFromJson = JSON.parse(json)

// the whole object
console.log(objFromJson)
console.log(objFromJson['/Inbound/tmp/ARTIFACTDOWNLOAD_DIR'])

// the elements one by one
for (let key in objFromJson) {
  objFromJson[key].forEach(item => {
    console.log(item)
  })
}
muka.gergely
  • 8,063
  • 2
  • 17
  • 34
0

Use JSON parser.

var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}');

Helpful link https://www.w3schools.com/js/js_json_parse.asp

Ankur Shah
  • 412
  • 6
  • 16