简体   繁体   English

将 JSON 字符串转换为 Typescript 中的 JAVASCRIPT 对象

[英]convert JSON string to JAVASCRIPT Object in Typescript

Hi every one I have two JSON string大家好,我有两个 JSON 字符串

[{desc:"john",number:"22",designation:"manager"}] [{desc:"john",number:"22",designation:"manager"}]

another JSON string另一个 JSON 字符串

[{name:"creek",ID:"198",role:"developer"}] [{名称:“小溪”,ID:“198”,角色:“开发人员”}]

so i need to map first JSON file with second JSON file所以我需要用第二个 JSON 文件映射第一个 JSON 文件

my output should be like this我的输出应该是这样的

[{desc:"creek",number:"198",designation:"developer"}] [{desc:"creek",number:"198",designation:"developer"}]

so here i thought while converting our JSON string to JAVASCRIPT object only we need to replace the attributes..所以在这里我想在将我们的 JSON 字符串转换为 JAVASCRIPT 对象时,我们只需要替换属性..

can any one help me with this Thanks...谁能帮我这个谢谢...

You have two distinct types, which we can define typescript types for.您有两种不同的类型,我们可以为它们定义打字稿类型。

type FormatOne = {
  desc: string;
  number: string;
  designation: string;
}

type FormatTwo = {
  name: string;
  ID: string;
  role: string;
}

We can create a function to map from one type to the other.我们可以创建一个函数来从一种类型映射到另一种类型。

const twoToOne = ({name, ID, role}: FormatTwo): FormatOne => ({
  desc: name,
  number: ID,
  designation: role,
})

When parsing JSON from a string, you have to assert the type with as because typescript does not know what the type will be.从字符串解析 JSON 时,您必须使用as来断言类型,因为 typescript 不知道类型是什么。 We can say that it will be an array with a mix of both types.我们可以说它将是一个混合了两种类型的数组。

const str = '[{desc:"john",number:"22",designation:"manager"}, {name:"creek",ID:"198",role:"developer"}]';
const arr = JSON.parse(str) as Array<FormatOne | FormatTwo>;

If you know that you have an array of all FormatTwo then reformatting it is as simple as calling array.map(twoToOne) .如果你知道你有一个所有FormatTwo的数组,那么重新格式化它就像调用array.map(twoToOne)一样简单。

When you have a mixed array, we need to check each element and conditionally call the converter.当你有一个混合数组时,我们需要检查每个元素并有条件地调用转换器。 We use 'name' in item as a type guard to see if the item is FormatTwo .我们'name' in item使用'name' in item作为类型保护来查看item是否为FormatTwo

const fixed = arr.map( item => 
  ('name' in item) ? twoToOne(item) : item
);

This new array fixed has the type FormatOne[] with no assertions required.这个fixed新数组具有FormatOne[]类型,不需要断言。

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

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