0

Trying to parse the JSON content from AWS SQS.

First converting a string to JSON String and then to JSON Object. What is the correct way to handle this scenario ?

<script>

// JSON from SQS 
var x='{"Message":"{\"default\":{\\\"key1\\\":\\\"value1\\\",\\\"key2\\\":\\\"value2\\\"}\"}","Timestamp":"2018-03-20T03:21:32.136Z"}';
x1=JSON.stringify(x);
var obj = JSON.parse(x1);
console.log(obj.Message); // undefined
alert(obj["Message"]); // undefined 
</script>
4
  • parse from string stringify to a string.. :) Commented Mar 20, 2018 at 21:13
  • What on earth are you doing to need all that escaping? Is the JSON rendered directly into your JS code, or is it retrieved by AJAX? Commented Mar 20, 2018 at 21:15
  • Firstly, you're stringifying a string. Secondly, you did not declare a variable for x1. Thirdly, your string is not a valid string. Open developers tool in chrome and run those expressions step by step and you'll see the error Commented Mar 20, 2018 at 21:58
  • that is the response I am getting from AWS SQS Commented Mar 20, 2018 at 21:58

2 Answers 2

1

I have absolutely no idea why you are trying to JSON.stringify() a string. It's already a string!

The string you have got is not valid JSON either and needs a few extra \\s in it. Where did you get it from? Or was it a typo.

var x='{"Message":"{\\\"default\\\":{\\\"key1\\\":\\\"value1\\\",\\\"key2\\\":\\\"value2\\\"}\\\"}","Timestamp":"2018-03-20T03:21:32.136Z"}';
                    ^__________^_____________________________________________________________^

Just parse the JSON you do have then realise that obj.Message is just more JSON that could be JSON.parse()d

// JSON
var x = '{"Message":"{\\\"default\\\":{\\\"key1\\\":\\\"value1\\\",\\\"key2\\\":\\\"value2\\\"}\\\"}","Timestamp":"2018-03-20T03:21:32.136Z"}';
//Parse JSON
var obj = JSON.parse(x);
console.log(obj.Message); // string formatted as yet more JSON

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

Comments

1

The string is not right. It should be like

var x='{"Message":"{\\\"default\\\":{\\\"key1\\\":\\\"value1\\\",\\\"key2\\\":\\\"value2\\\"}\\\"}","Timestamp":"2018-03-20T03:21:32.136Z"}';

You are stringifying the x, which is already string

x1=JSON.stringify(x); //Not ok

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.