Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 559
Serhii Zadorozhnyi Avatar asked Nov 30 '25 07:11

Serhii Zadorozhnyi


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.

like image 178
HMR Avatar answered Dec 02 '25 19:12

HMR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!