Mercurial > gemma
changeset 2423:3423cd4b3136
client: fix json parsing in identify box
JSON.parse() accepts integers and null as valid json. So to be sure to
get an object, we cannot just try JSON.parse() but we need to check if
the given value is a string and starts with a {.
author | Markus Kottlaender <markus@intevation.de> |
---|---|
date | Thu, 28 Feb 2019 15:34:07 +0100 |
parents | 77baf4f0ee1e |
children | b6deb03ef13f |
files | client/src/components/identify/Identify.vue |
diffstat | 1 files changed, 27 insertions(+), 13 deletions(-) [+] |
line wrap: on
line diff
--- a/client/src/components/identify/Identify.vue Thu Feb 28 14:51:03 2019 +0100 +++ b/client/src/components/identify/Identify.vue Thu Feb 28 15:34:07 2019 +0100 @@ -138,20 +138,20 @@ // create array with {key, val} objects let propsArray = []; Object.keys(feature.getProperties()).forEach(key => { - let val = feature.getProperties()[key]; + // skip geometry (would lead to cyclic object error) + if (key !== feature.getGeometryName()) { + let val = feature.getProperties()[key]; - // if val is a valid json string, parse it and spread its values into - // the array - try { - let json = JSON.parse(val); - Object.keys(json).forEach(key => { - propsArray.push({ key, val: json[key] }); - }); - } catch (e) { - // if val is not json then just put the key value pair into the array - // avoid cyclic object value (I didn't further investigate what's the - // problem here but feature.getGeometryName() needs to be skipped) - if (key !== feature.getGeometryName()) propsArray.push({ key, val }); + // if val is a valid json object string, spread its values into the array + let jsonObj = this.getObjectFromString(val); + if (jsonObj) { + Object.keys(jsonObj).forEach(key => { + propsArray.push({ key, val: jsonObj[key] }); + }); + } else { + // otherwise just put the key value pair into the array + propsArray.push({ key, val }); + } } }); @@ -168,6 +168,20 @@ }); return propsArray; + }, + getObjectFromString(val) { + // JSON.parse() accepts integers and null as valid json. So to be sure to + // get an object, we cannot just try JSON.parse() but we need to check if + // the given value is a string and starts with a {. + if ( + Object.prototype.toString.call(val) === "[object String]" && + val[0] === "{" + ) { + try { + return JSON.parse(val); + } catch (e) {} + } + return null; } } };