Skip to Content
Menu
This question has been flagged
2 Replies
2847 Views

I have a field of type char into which a string with json code will be inserted from parsing:

custom_data = fields.Char()

and I need to display this json in the form of html. It is reliably known that the json code will contain only the key, value, lang fields, for example:

[{"key":"rdhh","value":"sdasd","lang":"sada"},{"key":"rd123hh","value":"sd123asd","lang":"sad123a"},{"key":"rdh111h","value": "s111dasd","lang":"sa11da"},{"key":"rd44hh","value":"42sdasd","lang":"s4ada"},{"key":"rdhh6","value":"sd5asd","lang":"sa7da"}]


I did this with numpy, pandas libraries but I keep getting the message that my json code is equal to a binary value, even after I set it to default="[]".

Here is the code of my implementation:


personalization_html = fields.Html(string="Product property", compute='_json_conf')

def _json_conf(self):
cd = self.custom_data
names = ["key", "value", "lang"]

if cd == "[]":
df = pd.DataFrame(columns=names)
else:
z = json.dumps(cd)
y = json.loads(z)

arrs = []
for i in y:
value = []
value.append(i["key"])
value.append(i["value"])
value.append(i["lang"])

arrs.append(value)

a = np.array(arrs)

df = pd.DataFrame(a, columns=names)

return df.to_html(index=False)

I've been struggling with this for a week now, I've tried everything, but still nothing works...



Avatar
Discard
Author Best Answer
it didn't help me, but thanks to this code I rewrote my code and it worked)
def _compute_personalization_html(self):
cd = str(self.custom_data)
 
if cd == "False":
df = pd.DataFrame(columns=["#", "Key", "Value", "Lang"])
else:
custom_data = json.loads(cd)
data = []
num = 1
for row in custom_data:
data.append([num, row["key"], row["value"], row["lang"]])
num += 1

df = pd.DataFrame(data, columns=["#", "Key", "Value", "Lang"])

self.personalization_html = df.to_html(classes="table", index=False).replace('', '').replace(' border="1"', '')
Avatar
Discard
Best Answer

Hi,

Can you just try like this,

    custom_data = fields.Char(default="[]")
    personalization_html = fields.Html(string="Product property", compute='_compute_personalization_html')

    def _compute_personalization_html(self):
        for record in self:
            cd = record.custom_data
            names = ["key", "value", "lang"]

            if cd == "[]":
                html = ""
            else:
                data = json.loads(cd)
                rows = []
                for item in data:
                    row = [item.get("key", ""), item.get("value", ""), item.get("lang", "")]
                    rows.append(row)

                html = ""
                html += "".format(*names)
                for row in rows:
                    html += "".format(*row)
                html += "
{}{}{}
{}{}{}
"
record.personalization_html = html

Thanks

Avatar
Discard
Related Posts Replies Views Activity
3
Aug 24
6824
1
Sep 22
2846
0
Aug 22
2977
0
May 21
3212
2
Jun 25
892