我想在不使用 jQuery 的情况下为 Firefox 中的 Greasemonkey 创建一个用户脚本,它可以在加载网站页面时用新文本替换旧文本。
HTML代码:
..
window.app = profileBuilder({
..
"page": {
"btn": {
"eye": "blue",
"favorite_color": "blue",
"gender": "male",
},
},
..
});
..
将眼睛的“蓝色”替换为“绿色”,将喜欢的颜色的“蓝色”替换为“红色”,将“男性”替换为“女性”。
当页面加载时,我想看到,例如眼睛是绿色(不是蓝色),性别是女性(不是男性)。
我想接下来我需要使用函数:
GM_getValue()
GM_setValue()
JSON.parse()
JSON.stringify()
PS:代码JSON直接在页面中,而不是在文件(../code.json)中
用户脚本代码:
// ==UserScript==
// @name nemrod Test
// @namespace nemrod
// @include http*://mywebsite.com/*
// @version 1
// ==/UserScript==
var json = {"page": {"btn": {"eye": "blue","favorite_color": "blue","gender": "male",},},};
var stringified = JSON.stringify(json);
stringified = stringified.replace(/"eye": "blue"/gm, '"eye": "green"');
stringified = stringified.replace(/"favorite_color": "blue"/gm, '"favorite_color": "red"');
var jsonObject = JSON.parse(stringified);
没用
有人可以帮助编写正确的代码吗?
最佳答案
首先 stringify()
您的 JSON。
var stringified = JSON.stringify(json);
接下来,使用 .replace()
JavaScript 字符串函数。
stringified = stringified.replace('"eye": "blue"', '"eye": "green"');
stringified = stringified.replace('"gender": "male"', '"gender": "female"');
现在 parse()
将您的 JSON 转换为一个对象。
var jsonObject = JSON.parse(stringified);
现在,您可以根据需要使用 jsonObject
。
编辑:使用这些行代替之前的 .replace()
s。
stringified = stringified.replace('"eye": "blue"', '"eye": "green"');
stringified = stringified.replace('"gender": "male"', '"gender": "female"');
关于javascript - 如何用 Greasemonkey 的用户脚本替换 JSON 字符串中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28263868/