HarmonyOS json字符串转成map?

是否有json字符串转成map的方法呢?

阅读 449
1 个回答

JSON转换Map:如果是JSON字符串必须使用JSON.parse()转为对象;

使用 Object.entries() 接受对象返回二维数组;

let arr = Object.entries({"name":"张三","age":"18","address":"xian"});
console.log(arr)
// [["name","张三"],["age","18"],["address","xian"]]

//调用Map()构造函数
let arr = Object.entries({"name":"张三","age":"18","address":"xian"});
let map = new Map(arr);
console.log(map);

// {'name' => '张三', 'age' => '18', 'address' => 'xian'}

//JSON转换Map:
let jsonRecord:Record<string,Object> = JSON.parse('{ "0": {"num": 1}, "1": {"num": 2} }') as Record<string,Object>;
let map:Map<string,Object> = new Map();
Object.keys(jsonRecord).forEach((key) => {
  console.log(key + ': ' + jsonRecord[key]);
  map.set(key,jsonRecord[key]);
});
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进