I want to create a user script for Greasemonkey in Firefox without using jQuery, which can replace old text by new text when the page of website is loaded.
HTML code:
..
window.app = profileBuilder({
..
"page": {
"btn": {
"eye": "blue",
"favorite_color": "blue",
"gender": "male",
},
},
..
});
..
Replace "blue" of eye by "green", "blue" of favorite color by "red" and "male" by "female".
When the page will be loaded, I want to see, for instance Green (not Blue) for Eye and Female for Gender (not Male).
I guess I need to use functions next:
GM_getValue()
GM_setValue()
JSON.parse()
JSON.stringify()
PS: the code JSON is directly in the page and not in file (../code.json)
Userscript code:
// ==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);
It doesn't work
Can somebody help with the right code?
First stringify()
your JSON.
var stringified = JSON.stringify(json);
Next, use the .replace()
JavaScript String function.
stringified = stringified.replace('"eye": "blue"', '"eye": "green"');
stringified = stringified.replace('"gender": "male"', '"gender": "female"');
Now parse()
your JSON into an object.
var jsonObject = JSON.parse(stringified);
Now, you can use jsonObject
for whatever you want.
EDIT: Use these lines instead of the previous .replace()
s.
stringified = stringified.replace('"eye": "blue"', '"eye": "green"');
stringified = stringified.replace('"gender": "male"', '"gender": "female"');