Typescript key in json

Typescript json key how to know

More Details None of these options exist: «allow adding additional properties to a type after defining that type», «widen object literal type inference to include keys added after its declaration», «infer object literal types as types». In order for Pick to work I have to pass a type in the second parameter that is the intersection of the keys of the derived file type and PublicPrefix type.

How to get list of concatenated keys from json in typescript

I know that there are many threads about how to get keys from json, but I didn’t find my specific case. My question is a little more treaky. For example, consider this json:

I need to get a list of all nested keys, for example:

User.Usernames User.Roles User.Languages User.IsActive User.Family.Mother User.Family.Father Timestamp 
User Usernames Roles Languages IsActive Family Mother Father Timestamp 

I’m not interested to know the values of each key. I cannot search the key using the value because it can change every time. The code:

gives me only the root elements of the json (in this case «User» and «Timestamp»). I’m using typescript 2.9.2 with Angular 6.

let obj = < "User": < "Username": "testuser", "Roles": ["Chief", "Other"], "Languages": ["it", "en"], "IsActive": true, "Family": < "Mother": "Mary", "Father": "Mike" >>, "Timestamp": null > var list = []; getProps(obj); function getProps(obj, parent=null) < for (var props in obj) < if (typeof (obj[props]) == "object" && obj[props] !== null && !Array.isArray(obj[props]) ) < getProps(obj[props],props) >else if (parent !== null) < list.push(parent+"."+props); >else < list.push(props); >> > console.log(list); 

How can I get the key value in a JSON object?, Since you’re dealing with raw objects, the above for..in loop is fine (unless someone has committed the sin of mucking about with Object.prototype, but let’s assume not).But if the object you want the keys from may also inherit enumerable properties from its prototype, you can restrict the loop to only the object’s own …

Typescript JSON How do I read JSON using hierarchical key like «appInsights:instrumentationKey»

Given the below JSON, I should be able to read the JSON using hierarchical key path such as «appInsights:instrumentationKey». How can i do this in an angular project?

Читайте также:  Selecting an option in javascript

Is this what you are looking for ?

const obj = JSON.parse('your json'); const val1 = obj.appInsights.instrumentationKey; const val2 = obj['appInsights'].instrumentationKey; 

UPDATE: Will has fair point. If your JSON data doesnt contain user input e.g won’t contain anything harmful that will execute in browser then

const val = eval('obj.' + keyPath.replace(/:/g, '.')); 

Something along these lines perhaps:

getJsonProperty(jsonObj, keyPath: string)

If you don’t know how many levels the object can have, you could write a switch statement with cases for each accepted length of the keys Array. Obviously that means hard-coding each case (and a fixed maximum number of possible levels), unless there’s some other way of using String Literals I’m forgetting.

How do I convert definition typescript to json?, I want the contents of d.ts files to converted to json format i.e. I want the skeleton of functions in d.ts files to be shown in json or as an abstract syntax tree. I want to know how to proceed in order to achieve this. In a nutshell, I just want the existence of that particular function to be shown in the json file.

Type Definition for JSON file Keys with Prefix using TypeScript

I’m importing a JSON file into my TypeScript program like so: (I have enabled resolveJsonModule in my tsconfig.json )

import data from './sample.json'; 

Happily, I noticed that the object received from the JSON file is strongly typed. I then wrote a function which accesses a certain key of said JSON object based on a parameter:

export const get = (key: keyof typeof data): void => < console.log(dataTypescript key in json); // example code >; 

This works as expected, and consumers of my function get to know what values are accepted/included in the JSON file. Here comes the problem: I want consumers of my function to only be able to access certain keys which I’ve prefixed (in the following example the prefix is prefix_ ):

export const get = (key: keyof typeof data): void => < console.log(data[`prefix_$`]); >; 

How do I have to change my type definition so this will still work?

Prior to TypeScript 4.3

There’s no way as of TypeScript 4.2 to do a conditional type where you use a string function, so I don’t know of a way to specify a key that starts with a prefix.

The best I can come up with uses the Pick utility type to create a new type from the intersection of all possible properties and the derived types of the json files.

In the example below I import two sample json files. Next, I specify all the possible keys to keep in a string literal type. Then two types are created from the two files using Pick . In order for Pick to work I have to pass a type in the second parameter that is the intersection of the keys of the derived file type and PublicPrefix type.

import data1 from './sample1.json'; // < x: 1, prefix_A: 2, prefix_B: 3 >import data2 from './sample2.json'; // < y: 1, prefix_B: 2, prefix_C: 3 >type PublicPrefix = 'prefix_A' | 'prefix_B' | 'prefix_C'; export type Data1 = Pick; // Data1 = < prefix_A: number, prefix_B: number >export type Data2 = Pick; // Data2 =

If data1 has properties prefix_A and prefix_B , and data2 has the properties prefix_B and prefix_C , then the resulting types would be Data1 = < prefix_A, prefix_B >and Data2 = < prefix_B, prefix_C >with all other keys being excluded.

Читайте также:  Java jsonarray to list

Template String Literals in TypeScript 4.3

TypeScript 4 introduced Template String Literals, and in version 4.3 they’ve enhanced the functionality so you can specify a contextually typed template. This allows you to specify a type in the template which broadens those portions of the template to be anything valid for the type.

In the example below a template string literal is created that starts with prefix_ and is followed by any string. By using Pick in the same fashion as the above example, the resulting type will only contain the properties that begin with prefix_ .

import data from './sample.json'; type PublicPrefix = `prefix_$`; export type Data1 = Pick; 

How to let TypeScript know the keys of my object?, Notice that the keys of the objects are not known. For instance one could be: const a: StyleSet = < potato: < width: '100%', >, > while another object could be: const b: StyleSet = < ketchup: < width: 'auto', >, > Also notice that there is a partial solution for this, using ReturnType TypeScript can do what I want but I would …

TypeScript: How to edit tsconfig.json to allow add keys to existing object?

I want the following working by default:

I know there are some other workarounds, I just want to know if I can make it work by only editing tsconfig.json ?

tsconfig.json does not have an option to make all objects to default to something like type . Even if it did, TypeScript would probably still need to know what type your keys and values are.

As a suggestion, you should type j with the following:

I know there are some other workarounds, I just want to know if I can make it work by only editing tsconfig.json?

Short Answer

There is no tsconfig.json option for that.

More Details

None of these tsconfig.json options exist:

  • «allow adding additional properties to a type after defining that type»,
  • » widen objectLiteral Type inference to include keys added after its declaration»,
  • » infer object literal types as Record types».
Читайте также:  Linkedlist in java example

As a result, there is no tsconfig.json option that will allow this:

That is because TypeScript infers the type of object literals at the time of assignment. As a result, your original code is the equivalent of this.

Javascript — How to check whether a JSON key’s value is, My goal is to create an if statement that would detect whether the value of the key is an Array or just a value, without knowing the name of the key (in above code let’s assume I don’t really know the name of «attributes»). How do I achieve that? Not only do I have to loop through all person objects, but also all of …

Источник

How to check if a json object has a key in typescript?

TypeScript almost has the same syntax as javascript to check object has a key or not, in this tutorial, we will learn multiple ways to check object has a key or not in typescript.

Now, we are going to learn below three ways to check object keys exist or not.

Let start today’s tutorial How to check if a JSON object has a key in typescript?

Before we move to check all three methods with examples, let first create an example object which we can use in all the below examples.

interface userInterface   id: number,  name: string, >;  let user: userInterface =  id: 1, name: 'infinitbility' >; 

hasOwnProperty() method#

When inheritance is an important part of the structure of your application, the difference is that it will result in true even for properties inherited by parent objects. hasOwnProperty() doesn’t. It will only return true if the object has that property directly — not one of its ancestors.

interface userInterface   id: number,  name: string, >;  let user: userInterface =  id: 1, name: 'infinitbility' >;  user.hasOwnProperty("id"); user.hasOwnProperty("example"); 

Output#

hasOwnProperty, typescript, Example

if..else method#

if..else also can handle to check key exists or not in objects.

Here is a list of falsy values:

  • false
  • 0 (zero)
  • -0 (negative zero)
  • 0n (BigInt zero)
  • «», », « (empty string)
  • null
  • undefined
  • NaN (not a number)
interface userInterface   id: number,  name: string, >;  let user: userInterface =  id: 1, name: 'infinitbility' >;  if(user.id)  true; > else   false; >  if(user.example)  true; > else   false; > 

Output#

if..else, typescript, Example

() ? : ; ternary method#

Ternary method work like the same if..else method, but you can use it as a shorthand.

interface userInterface   id: number,  name: string, >;  let user: userInterface =  id: 1, name: 'infinitbility' >;  (user.id) ? true : false; (user.example) ? true : false; 

Источник

Оцените статью