在 Freemarker 中将字符串转换为 JSON

问题描述 投票:0回答:2

关于如何将

VALID JSON STRING
转换为
freemarker
中的实际 JSON(序列)的任何方法。我的意思是这个字符串实际上是由
JSON.stringify()
调用返回的。

我遵循这个post所说的,但似乎这不适用于我的。

<#assign test = "(record.custpage_lineitems?json_string)">
<#assign m = test?eval>

<#list m as k>
    ${k.item}
</#list>
ERROR says
Expected collection or sequence. m evaluated instead to freemarker.template.SimpleScalar on line 286, column 32 in template.
Sample JSON String
{
"34952": {
    "item": "TRAVEL",
    "notes": "Travel Time To Client Site to Perform Repairs.1.0",
    "type": "Service"
},
"34963": {
    "item": "MECHANIC RECOMMENDATION",
    "notes": "MECHANIC RECOMMENDATION\nr&r drive tires 21x7x15 smooth black \nr&r lp tank latch on bracket \nr&r lp hose cupler",
    "type": "Service"
},
"9938": {
    "item": "T1",
    "notes": "Field Service Call Charge75$ labor 124$",
    "type": "Service"
},
"34549": {
    "item": "GENERAL SERVICE INFO",
    "notes": "SERVICE NOTES:\ndrove to customer location found lift found to broken hydraulic hoses had to remove attachment in order to remove broken hoses then drove to get hoses made installed hoses back on lift re installed loose brackets I found out attachment back on lift topped off hydraulic resivoir and lift was ready",
    "type": "Service"
},
"36264": {
    "item": "FSO PARTS (UN CHECK IF NEEDED)",
    "notes": "MARK CHECK IF PARTS NOT NEEDED.",
    "type": "Service"
},
"36266": {
    "item": "FSO QUOTE (UN CHECK IF NEEDED)",
    "notes": "MARK CHECK IF QUOTE NOT NEEDED.",
    "type": "Service"
},
"29680": {
    "item": "0199992-HY32F",
    "notes": "2 x 0199992-HY32F",
    "type": "Inventory Item"
}

}

它似乎没有转换为有效的序列,因为如果我尝试打印

${m}
,它会显示转义的 json 字符串。

我正在寻找一种方法,我只会说

<#assign test=toJSON(record.custpage_lineitems)
,但我认为你必须用java编写方法,因为我在“netsuite”中这样做

更新:我尝试对 json 字符串进行硬编码,如

<#assign m = '{"34952":{"item":"TRAVEL","notes":"Travel Time To Client Site to Perform Repairs.1.0","type":"Service"}....}'>

并尝试循环,它似乎有效。但如果我将

m
的值替换为
myvariable
似乎不起作用。我 100% 确定
myvariable
不为 null 也不为空,但包含相同的 JSON 字符串。

我的评估是,如果我可以将

myvariable
包装到
single quote
那么我认为它会解决问题。我试过了

<#assign m = 'myvariable'> and
<#assign m = '(myvariable)'> and 
<#assign m = '(${myvariable})'> and 
<#assign m = '(myvariable?string)'> etc.

但没有一个是正确的。有人可以指导我了解如何将现有变量包装为单引号的正确语法吗?

大家有什么帮助吗?谢谢。

json freemarker netsuite
2个回答
0
投票

我认为 json 字符串中的

\n
可能会导致一些问题。尝试先将其替换为(或类似的适合您需要的东西)

record.custpage_lineitems?replace("\n", "\\n")

然后然后

eval


0
投票

如果您的

record.custpage_lineitems
已经是字符串化的 JSON,那么您不必使用
?json_string

将前两行替换为:

<#assign m = record.custpage_lineitems?eval>

有关详细信息,请参阅eval文档。


更新: 你的

custpage_lineitems
是一个哈希映射,#list 接受序列。试试这个:

<#list m?keys as k>
    ${m[k].item}
</#list>
© www.soinside.com 2019 - 2024. All rights reserved.