【问题标题】:How to assign JSON string to a variable?如何将 JSON 字符串分配给变量?
【发布时间】:2019-08-19 04:18:42
【问题描述】:

我正在尝试将表单输入数据发送到 REST SERVICE。 现在的格式是

{
  "locationname":"test",
  "locationtype":"test",
  "address":"test"
}

但服务接受格式是

 {
    "value": "{ locationname: test ,locationtype: test, address:test }",
 }

试图用下面的字符串转换

const tests = JSON.parse(JSON.stringify(Form.value));

但是如何分配给Value

我期待表单提交后的结果

{
  "value":"{ locationname: test ,locationtype: test, address:test }",
}

【问题讨论】:

  • const tests = JSON.stringify({ value : JSON.stringify(Form.value) });
  • @Pranav C Balan 赋值完成但参数仍为字符串格式 { "value":"{ "locationname": "test" ,"locationtype": "test", "address" :"测试" }", }
  • 如果您需要一个属性值为 JSON 字符串的对象,请使用 const tests = { value : JSON.stringify(Form.value) };
  • 它作为[object object]发送
  • 您的要求不清楚

标签: json typescript angular6


【解决方案1】:

也许这符合您的要求。 “modifiedJsonObject”应该是你需要提交的。

const formValue = JSON.parse('{"locationname":"test","locationtype":"test","address":"test"}');
    const formValueString = JSON
      .stringify(formValue)
      .replace(/"/g, '');
    const modifiedJsonObject = { value: formValueString };
    const jsonString = JSON.stringify(modifiedJsonObject);

    // jsonString = '{"value":"{locationname:test,locationtype:test,address:test}"}'

【讨论】:

  • 如何在 html 中打印值,端点给出响应为 ["id": 1, '{"value":"{name:test,type:test,address:test}"}' , "id":2, '{"value":"{name:test1,type:test1,address:test1}"}'];
  • 首先给定的响应代表一个元素数组。它也不是一个有效的 json。所以你必须解析整个字符串,得到代表值的字符串。
猜你喜欢
  • 1970-01-01
  • 2018-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-08
  • 2013-05-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多