How to parse JSON with random fields in Typescript and React.js

Viewed 2222

Have Json string with random fields in Typescript( I don't know what kind of fields inside of json string or their types). Want parse json string to object with default type of fields for example string.

Parsing like this: let values = JSON.parse(this.props.values!)

Having error when working with React.js, because of type unknown. Also can't predefine interface because I don't know what inside json string

Object.entries(values).map(([key, value]) => {
                renderValues = (
                    <>
                        <div className="col-1 text-left p-2" ></div>
                        <div className="col-2 text-right p-2" >{key}</div>
                        <div className="col-9 text-left p-2" >{value}</div>
                    </>)
            })

Have error: Type 'unknown' is not assignable to type 'ReactNode'. Type 'unknown' is not assignable to type 'ReactPortal'.ts(2322) index.d.ts(1244, 9): The expected type comes from property 'children' which is declared here on type 'DetailedHTMLProps, HTMLDivElement>'

How in typescript when parsing json string to object give to object fields default type or cast object fields to default type?

1 Answers

As commented; can you try the following:

renderValues = Object.entries(values).map(
  ([key: string, value: string]) => (
    <>
      <div className="col-1 text-left p-2"></div>
      <div className="col-2 text-right p-2">{key}</div>
      <div className="col-9 text-left p-2">{value}</div>
    </>
  )
);

And please read the link I posted before because you are not using Array.prototype.map correctly.

Related