正则表达式匹配对象数组中的键val

时间:2018-02-15 17:06:24

标签: javascript regex

使用https://regexr.com/我一直在尝试匹配数据对象中的各个部分。

JSON

{"unit":{"id":1,"val":"px","name":"px"},"type":{"id":3,"val":"HORIZONTAL_BAR","name":"Horizontal Bar"},"zoom":{"id":2,"val":"DEFAULT","name":"Show"},"scale":{"id":2,"val":"TRUE","name":"Show"},"fullscreen":{"id":1,"val":"FALSE","name":"Hide"},"street":{"id":2,"val":"TRUE","name":"Show"},"poi":{"id":1,"val":"FALSE","name":"Disable"},"draggable":{"id":2,"val":"TRUE","name":"Enable"},"doubleclick":{"id":2,"val":"TRUE","name":"Enable"},"mouse":{"id":2,"val":"TRUE","name":"Enable"},"gesture":{"id":2,"val":"auto","name":"Auto"},"map":{"id":1,"val":"ROADMAP","name":"Road Map"},"mapid":"mapkit-9479","api":"","lat":"51.343695608206275","lng":"-2.4871419408111706","zoomlvl":13,"width":600,"height":400,"position":{},"route":{},"infowindow":{"enable":false,"title":false,"tel":false,"email":false,"web":false,"desc":false},"visible":1,"lon":"-2.4871419408111706","user_id":4575,"map_url":"26T9Te","snazzy":{"id":12,"snazzy_id":11,"name":"Blue","json":"[{\"featureType\":\"all\",\"stylers\":[{\"hue\":\"#0000b0\"},{\"invert_lightness\":"true"},{\"saturation\":-30}]}]"}}

这是json的一个例子,如果你是lint它,它将失败主要是由于这个段。

{\"invert_lightness\":"true"}

我尝试做的是使用REGEX来匹配和替换以解决问题

我已经尝试了\\"(.*)\\":"(.*)",因为我认为它会匹配任何没有斜杠的",我可以用斜杠替换它。所以它看起来像{\"invert_lightness\":\"true\"}并修复它。

但是我写的正则表达式查询以一个匹配结束:

\"featureType\":\"all\",\"stylers\":[{\"hue\":\"#0000b0\"},{\"invert_lightness\":"true"},{\"saturation\":-30}]}]"

2 个答案:

答案 0 :(得分:1)

似乎你可以使用

\\"(.*?)\\"

并将其替换为

"$1"

a demo on regex101.com

<小时/> 这说:

\\"   # match one backslash and "
(.*?) # capture 0+ characters in between, lazily into group 1
\\"   # same as above

答案 1 :(得分:0)

试试这个:

str.replace(/\\"/g, '"').replace(/"\[/g, '[').replace(/\]"/, ']')