0

I'm trying to parse a multi-line JSON response to get a value for a key using JavaScript. I read we can't parse multi-line json, how I can achieve getting "Created" value from below json?

  1. I tried converting the JSON to string and used replace to converting multi-line to single line with \n as deliminator. -- Unable to replace multi-liner text.

  2. I tried extracting index of mischief key value and remove from the string -- Syntax error.

    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);
    

My expectation is to get 2015-05-22T14:56:29.000Z as output.

2 Answers2

1

In your example i see syntax error

Try to change string definition "" to ``

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)
Vadim Hulevich
  • 1,803
  • 8
  • 17
0
  • In case of new line you can replace all the new lines and then parse the JSON.
  • Each OS generate different newline characters you need to be aware of that while replacing newline characters.

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);
Raheel Anwar
  • 267
  • 2
  • 10