简体   繁体   中英

How to extract all keys and values from json? using Javascript

I have like this json.

{
  "a": 99,
  "b": "this, is, string",
  "c": "hi:"
}

I want to extract all keys and value to a array like this. 在此处输入图像描述

But split(',') is not working because there are multiple , in "b": "this, is, string", . Even I can't split using : because there's : in hi:, .

Could you give me some advice?

You can use Object.entries with .flat :

 const fixedJson = `{ "a": 99, "b": "this, is, string", "c": "hi:" }`; const obj = JSON.parse(fixedJson); const result = Object.entries(obj).flat(); console.log(result);

You can use Object.keys() and Object.values() to get seperated array with keys and values. Then you can merge these two arrays.

 const str = `{ "a": 99, "b": "this, is, string", "c": "hi:" }`; const d = JSON.parse(str); const k = Object.keys(d); const v = Object.values(d); const t = Math.min(k.length, v.length); const m = [].concat(...Array.from({ length: t }, (_, i) => [k[i], v[i]]), k.slice(t), v.slice(t)); console.log('merged', m)

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