0

I have a json in a textarea {"request":{"method":"GET","url":"/thing/1"},"response":{"status":200}}

I have a function currently which gets the value from my textarea and replaces

    function setFontText(text) {
        var str=document.getElementById("urls").value;
        var res = str.replace(/"url":"/g, "&quoturl&quot:&quot" + text + "&quot");
        document.getElementById("urls").innerHTML=res;
    }

I am currently replacing only "url:"/ however I would like to completely replace ( The Italicized section ) "url":"/thing/1" but the part in bold is dynamic here so I do not want to hardcode in my code like str.replace(/"url":"/thing/1"/g

Is there a workaround for this ? If the question isn't clear please revert

5
  • You should use value or innerHTML consistently, not use one for getting the value but the other one for setting it. Commented Aug 4, 2019 at 17:17
  • Thanks for the tip TJ, surprisingly the ans from Javas worked for me but if you seem to have a workaround for this I'd be interested to know that too Commented Aug 4, 2019 at 17:21
  • 2
    An alternative would be parse the json string to object and use object methods on it, then stringify modified result Commented Aug 4, 2019 at 17:23
  • No, just a side note about the properties you're using. I haven't checked it closely, but Javas answer looks roughly correct. (Also note that you're missing the ; on ".) Commented Aug 4, 2019 at 17:24
  • @charlietfl - I wouldn't exactly be sure on how to go about this, Do you mind explaining it please ? through an answer maybe. I haven't thought about this option Commented Aug 4, 2019 at 17:40

2 Answers 2

3

Assuming the structure is consistent you can parse the string to object then modify that object and stringify the result

function setFontText(text) {
  const str = document.getElementById("urls").value,
        obj = JSON.parse(str);
  obj.request.url = text;
  document.getElementById("urls").innerHTML = JSON.stringify(obj);
}

setFontText('/MyTest')
<textarea id="urls" cols=60 rows=6>
{"request":{"method":"GET","url":"/thing/1"},"response":{"status":200}}
</textarea>

Sign up to request clarification or add additional context in comments.

Comments

2

When you parse the json to a javascript object you can easily delete or alter properties. After that just generate a new json from the object again.

var json = '{"request":{"method":"GET","url":"/thing/1"},"response":{"status":200}}';
var jsonResult = JSON.parse(json);
jsonResult.request.url = 'newtext';
var newJson = JSON.stringify(jsonResult);
console.log(newJson);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.