【问题标题】:How to access a JSON string inside a JSON string - JavaScript如何访问 JSON 字符串中的 JSON 字符串 - JavaScript
【发布时间】:2018-10-16 03:35:23
【问题描述】:

我的 JSON 字符串:

[{ "foo":"bar", "foo2":"[{ "test":"test", "test2":"test2" }]" }]

我想获取foo2 的值作为新的 JSON 字符串。

我已经尝试了这些代码,但它不会工作:

myObj[1]["test"];

【问题讨论】:

  • 外部数组中只有一个项目。此外,如果您有 JSON,则需要使用 JSON.parse 解析它。 (否则,你没有 JSON,你只有一个对象)
  • 我已经尝试解析该值,但它总是输出undefined
  • 简单google就可以解决问题,@winmar014请先搜索

标签: javascript arrays json


【解决方案1】:

你必须先获取 foo2 然后从 foo2 测试 myObj[0]['foo2'][0]["test"];

【讨论】:

    【解决方案2】:

    获取 foo2 的值作为新的 JSON 字符串

    var myObj = [{
      "foo": "bar",
      "foo2": '[{ "test":"test", "test2":"test2" }]' /* replaced enclosing quotes " with ' */
    }];
    console.log(myObj[0]['foo2']); /* replaced 1 with 0 */

    【讨论】:

      【解决方案3】:

      var obj = [{
        "foo": "bar",
        "foo2": '[{ "test":"test", "test2":"test2" }]'
      }];
      var foo2 = JSON.parse(obj[0]['foo2']);
      console.log(foo2[0]['test']);

      【讨论】:

        猜你喜欢
        • 2023-04-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多