简体   繁体   English

如何从 json 中提取所有键和值? 使用 Javascript

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

I have like this json.我喜欢这个 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", .但是split(',')不起作用,因为有多个, in "b": "this, is, string", Even I can't split using : because there's : in hi:, .即使我不能使用:拆分,因为:hi:,中。

Could you give me some advice?你能给我一些建议吗?

You can use Object.entries with .flat :您可以将Object.entries.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.您可以使用Object.keys()Object.values()来获取包含键和值的分离数组。 Then you can merge these two arrays.然后就可以合并这两个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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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