How to access attributes of a JSON that has been converted with special characters?

Asked

Viewed 193 times

1

I am consuming the API of microsoft translation, they work with the return in XML(Because it is, MICROSOFT returns XML in its API’S), I managed to run everything right, but as I hate working with XML I decided to convert XML to JSON, with the library Json.NET, the response of the XML translation is:

<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">Mechanical</string>

When I convert to JSON through Json.NET:

XmlDocument doc = new XmlDocument();
doc.LoadXml(response.Content);
string json = JsonConvert.SerializeXmlNode(doc);
Debug.WriteLine(json);

I get it:

{"string":{"@xmlns":"http://schemas.microsoft.com/2003/10/Serialization/","#text":"mechanical"}}

If I try to access string.#text i get an error in browser:

Syntaxerror: illegal Haracter

How to access #text whether the format converter is adding special characters in the attributes name? I noticed this occurs in the own example json.NET

  • Is that a default xmlns="http://schemas.microsoft.com/2003/10/Serialization/ ? That’s always in the answer?

  • @Perozzo yes, this answer is standard API

  • 1

    @Perozzo ;)

  • Good! I was going to suggest to remove xmlns="http://schemas.microsoft.com/2003/10/Serialization/" from Sponse. Content before converting, but since you got it right, better.

1 answer

1


When there are special characters in the attribute name, just call it with conchetes([]).

{"string":{"@xmlns":"http://schemas.microsoft.com/2003/10/Serialization/","#text":"mechanical"}}

Access #text thus:

console.log(string["#text"]); //mechanical

Browser other questions tagged

You are not signed in. Login or sign up in order to post.