如何使用RegEx从JSON获取所有字符串值,而不是键?

时间:2016-06-07 15:22:12

标签: json regex

这是我到目前为止的正则表达式,但它正在选择键。我只想选择所有出现的值:https://regex101.com/r/fA5cP9/1

{
    "contact": {
        "name": "John Doe",
        "label": "Web Developer",
        "email": "email@example.com",
        "phone": "(123) 123-1234",
        "website": "www.example.com",
        "profiles": [{
            "network": "LinkedIn",
            "url": "www.linkedin.com"
        }]
    }
}

1 个答案:

答案 0 :(得分:1)

因为这不是一个真正需要解决的现实世界问题,所以坚持使用RegEx方法可能最容易。

您的RegEx几乎是正确的,您只是忘记了一件事:区分键和值的唯一因素是两者之间的冒号。每个值前面都是冒号,因此您必须将RegEx更改为\:\s?\"(.*?)\"\s?确保它有效,即使冒号后面有空格。

现在您需要对JSON进行字符串化,进行替换,然后重新解析它:

var resume = {
    "contact": {
        "name": "John Doe",
        "label": "Web Developer",
        "email": "email@example.com",
        "phone": "(123) 123-1234",
        "website": "www.example.com",
        "profiles": [{
            "network": "LinkedIn",
            "url": "www.linkedin.com"
        }]
    }
};

var greekedResume = JSON.parse(JSON.stringify(resume)
    .replace(/:\s?\"(.*?)\"/g, ":\"Lorem ipsum\""));
相关问题