asdf31
asdf31

Reputation: 268

How to make json format valid?

I generated a string that contains a json in my C# codebehind, then I send it to the frontend to use in Javascript. I want to use that json inside a function like $.getJSON("<%=myJson%>") but I'm getting some errors

I already tried to use the string directly since json is javascript code but it doesn't work. The console shows

"Uncaught SyntaxError: missing ) after argument list"

Then I tried JSON.parse(myJson) but it´s also not working. The console shows

"Uncaught SyntaxError: Unexpected identifier"

This is how my Json string looks in codebehind:

"\"iss\":\"123123123\",\"exp\":123123,\"jti\":\"asdasdasdasd\",\"sub\":\"asdasdasdasd\",\"grants\":{\"identity\":\"John\",\"voice\":{\"incoming\":{\"allow\":true},\"outgoing\":{\"application_sid\":\"asdasdasdasd\"}}}}"

Then when I send it to Javascript in the frontend:

$.getJSON("
"iss":"123123123","exp":123123,"jti":"asdasdasdasd","sub":"asdasdasdasd","grants":{"identity":"John","voice":{"incoming":{"allow":true},"outgoing":{"application_sid":"asdasdasdasd"}}}}")

UPDATE I fixed the json syntax in codebehind:

"{\"iss\":\"123123123\",\"exp\":123123,\"jti\":\"asdasdasdasd\",\"sub\":\"asdasdasdasd\",\"grants\":{\"identity\":\"John\",\"voice\":{\"incoming\":{\"allow\":true},\"outgoing\":{\"application_sid\":\"asdasdasdasd\"}}}}"

now I'm getting this error in javascript:

$.getJSON('{"iss":"123123123","exp":123123,"jti":"asdasdasdasd","sub":"asdasdasdasd","grants":{"identity":"John","voice":{"incoming":{"allow":true},"outgoing":{"application_sid":"asdasdasdasd"}}}}')

GET http://localhost:.... 400 (Bad Request)

I think it's because this function expects a url to access but how can I make it read my json string?

Upvotes: 0

Views: 144

Answers (2)

Teiem
Teiem

Reputation: 1619

your json is wrong, you are missing a { at the beginning. The following function should work:

JSON.parse(`{"iss":"123123123","exp":123123,"jti":"asdasdasdasd","sub":"asdasdasdasd","grants":{"identity":"John","voice":{"incoming":{"allow":true},"outgoing":{"application_sid":"asdasdasdasd"}}}}`)

Upvotes: 1

Barmar
Barmar

Reputation: 780899

Use single quotes around the JSON in the JavaScript code, since JSON uses double quotes for the embedded strings.

$.getJSON('<%= myJson %>');

You also need to fix the code that's creating myJson in the first place, so that it's correctly formatted as JSON. See How to create JSON string in C#

Upvotes: 1

Related Questions