【问题标题】:How to parse multi-line JSON response to exact a particular key's value?如何解析多行 JSON 响应以精确特定键的值?
【发布时间】:2019-08-07 11:41:23
【问题描述】:

我正在尝试解析多行 JSON 响应以使用 JavaScript 获取键的值。我读到我们无法解析多行 json,我如何才能从下面的 json 中获取“Created”值?

  1. 我尝试将 JSON 转换为字符串,并使用替换将多行转换为单行,并使用 \n 作为分隔符。 -- 无法替换多行文本。

  2. 我尝试提取恶作剧键值的索引并从字符串中删除 -- 语法错误。

    var v1 =  {
        "data": {
            "type": "articles",
            "id": "1",
            "attributes": {
                "title": "JSON:API paints
    my bikeshed!",
                "body": "The shortest article. Ever.",
                "created": "2015-05-22T14:56:29.000Z",
                "updated": "2015-05-22T14:56:28.000Z"
            },
            "relationships": {
                "author": {
                    "data": {
                        "id": "42",
                        "type": "people"
                    }
                }
            }
        }
    };
    alert(result.data.attributes.created);
    

我的期望是得到 2015-05-22T14:56:29.000Z 作为输出。

【问题讨论】:

标签: javascript json jsonparser


【解决方案1】:

在您的示例中,我看到语法错误

尝试将字符串定义 "" 更改为 ``

var v1 =  {
    "data": {
        "type": "articles",
        "id": "1",
        "attributes": {
            "title": `JSON:API paints
my bikeshed!`,
            "body": "The shortest article. Ever.",
            "created": "2015-05-22T14:56:29.000Z",
            "updated": "2015-05-22T14:56:28.000Z"
        },
        "relationships": {
            "author": {
                "data": {
                    "id": "42",
                    "type": "people"
                }
            }
        }
    }
};

console.log(v1.data.attributes.created)

【讨论】:

    【解决方案2】:
    • 如果有新行,您可以替换所有新行,然后解析 JSON。
    • 每个操作系统都会生成不同的换行符,您需要 替换换行符时请注意这一点。

    var v1 =  `{
        "data": {
            "type": "articles",
            "id": "1",
            "attributes": {
                "title": "JSON:API paints
    my bikeshed!",
                "body": "The shortest article. Ever.",
                "created": "2015-05-22T14:56:29.000Z",
                "updated": "2015-05-22T14:56:28.000Z"
            },
            "relationships": {
                "author": {
                    "data": {
                        "id": "42",
                        "type": "people"
                    }
                }
            }
        }
    }`;
    
    var result = v1.replace(/(?:\r\n|\r|\n)/g, '');
    
    var resultObj = JSON.parse(result);
    
    console.log(resultObj.data.attributes.created);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-09
      • 1970-01-01
      • 1970-01-01
      • 2012-09-20
      相关资源
      最近更新 更多