-2

I'm new to javascript and JSON objects and I'm wondering, is there a way to search for a keyword within the value of one of the key/value pairs?

My JSON objects have various key/value pairs and one of them is the Message key shown here...

Message: "<?xml version="1.0" encoding="UTF-8" ?><Response Version="2.3 Build Date 15/06/2020" Type="SNMPQuery" Timestamp="1592321768"><State>"Up"</State><SNMPResponse>""</SNMPResponse></Response>"

In dev tools I can query the Message key through dot notation and therefore see the value, but is there a way to just query/return the State of the Server, so in this case the word "Up"?

I hope all this makes sense.

Thanks

mgl_lpz_
  • 13
  • 1
  • 1
    Get an XML parsing library, parse the XML, access the resulting object properties. – jonrsharpe Jul 29 '20 at 14:34
  • 1
    1. [There is no such thing as JSON objects](https://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation). It's *either* JSON *or* a JavaScript object. In your case, it seems it's the latter. 2. Your best bet is to read this as XML and then probably use xpath or manually navigate to read the value. – VLAZ Jul 29 '20 at 14:34
  • @jonrsharpe [DOMParser](https://developer.mozilla.org/en-US/docs/Web/API/DOMParser) can natively read XML. There might be no need for a library. – VLAZ Jul 29 '20 at 14:35
  • @VLAZ true, but that's not available if the OP is trying to access this on the server/Node side. – jonrsharpe Jul 29 '20 at 14:36

1 Answers1

0

You can use DOMParser to parse the XML.

var res = {
  Message: '<?xml version="1.0" encoding="UTF-8" ?><Response Version="2.3 Build Date 15/06/2020" Type="SNMPQuery" Timestamp="1592321768"><State>"Up"</State><SNMPResponse>""</SNMPResponse></Response>'
};
let doc = new DOMParser().parseFromString(res.Message, "text/xml");
console.log(doc.querySelector('State').textContent);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80