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>
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
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
Related
I'm using Editor.js which outputs data as JSON and save that as String in DynamoDB. When I query that data, I want to convert that back to an Object.
Converting the string with JSON.parse() gives me Error: Unexpected token t in JSON at position 1 message.
var json = '{time=1558311121067, blocks=[{type=paragraph, data={text=writing something first}}], version=2.13.0}';
obj = JSON.parse(json);
Not sure what this error message means.
I will suggest to correct the JSON from the origin itself if you can,
if you can't than you need to replace = with : and than stringify and parse
({[^=]+|,[^=]+)=
| |_________ Replaces `=` which is preceded by `,`
|_________________ Replaces `=` which is preceded by `{`
let json = '{time=1558311121067, blocks=[{type=paragraph, data={text=writing something first}}], version=2.13.0}';
json = json.replace(/({[^=]+|,[^=]+)=/g,"$1"+':')
let obj = JSON.parse(JSON.stringify(json));
console.log(obj)
On side note:- This is code is considering above given example data, it can be updated based on the kind of values your JSON can have
I would like to convert my json to a string then find and replace substrings like so using JQuery
var data = JSON.stringify(object).text();
data.text(data.replace("meat", "vegetables"));
console.log(data);
This gives me
JSON.stringify(...).text is not a function
How can I fix this.
JSON.stringify is already a text (string), that's what stringify means (turn to a string), just omit the .text():
var object = {"food":"meat","quantity":"10"}
var data = JSON.stringify(object); // this is a string
data = data.replace("meat", "vegetables");
console.log(data);
The method stringify returns string and the type string doesn't have the method text, so just update the first line to the following:
var data = JSON.stringify(object);
also update the second line with the following:
data = data.replace("meat", "vegetables");
Here is my code
var data = '{"coord":{"lon":74.34,"lat":31.55},"weather":[{"id":711,"main":"Smoke","description":"smoke","icon":"50d"},{"id":701,"main":"Mist","description":"mist","icon":"50d"}],"base":"cmc stations","main":{"temp":304.6,"pressure":1002,"humidity":62,"temp_min":304.15,"temp_max":305.15},"wind":{"speed":5.1,"deg":130},"clouds":{"all":20},"dt":1466901000,"sys":{"type":1,"id":7133,"message":0.0035,"country":"PK","sunrise":1466899176,"sunset":1466950287},"id":1172451,"name":"Lahore","cod":200}'
setWeather(data);
function setWeather(data) {
var json = JSON.parse(JSON.stringify(data));
alert(json['main']['temp']);
$('#temp').html(json['main']['temp']);
}
And I can't seem to figure out why I'm not able to access the json object parameter. Anyone know what the issue is?
Thanks in advance.
Let us to some basic debugging:
> var data = '{"coord": ... }';
> typeof data
"string"
So far so good, data is a string.
> JSON.stringify(data);
""{\"coord\": ... }""
> typeof JSON.stringify(data);
"string"
Apparently JSON.stringify(data) also returns a string. We can see the same value contained in data but now including surrounding quotes (note the double "" at the beginning and the end) and escaped quotes (\").
So what exactly does JSON.stringify do? It will convert any JavaScript value to JSON. Some examples:
> JSON.stringify([]) // array
"[]"
> JSON.stringify(true) // array
"true"
> JSON.stringify("foo") // string
""foo""
We can see that passing a string simply produces another JSON encoded string, so that doesn't seem particular helpful. But you are also using JSON.parse, so lets see what effect that has:
> JSON.parse(JSON.stringify(data))
"{"coord": ... }"
> typeof JSON.parse(JSON.stringify(data))
"string"
It seems using JSON.parse returns a string again. This shouldn't be too surprising since we are passing a string value to JSON.stringify, which will encode it as a JSON string. Parsing this result must give us back the original value, which was a string. We can verify that easily:
> JSON.parse(JSON.stringify(data)) === data
true
Yep.
So that doesn't help us converting data to a JavaScript object. Lets just try JSON.parse instead:
> JSON.parse(data)
Object {coord: Object, weather: Array[2], base: "cmc stations", main: Object, wind: Object…}
That looks much better. Since data contains a JSON encoded object, JSON.parse converts that value to a JavaScript object.
I your example, data is a string, not a javascript object, so you don't need to use JSON.stringify, remove it and it should work:
var data = '{"coord":{"lon":74.34,"lat":31.55},"weather":[{"id":711,"main":"Smoke","description":"smoke","icon":"50d"},{"id":701,"main":"Mist","description":"mist","icon":"50d"}],"base":"cmc stations","main":{"temp":304.6,"pressure":1002,"humidity":62,"temp_min":304.15,"temp_max":305.15},"wind":{"speed":5.1,"deg":130},"clouds":{"all":20},"dt":1466901000,"sys":{"type":1,"id":7133,"message":0.0035,"country":"PK","sunrise":1466899176,"sunset":1466950287},"id":1172451,"name":"Lahore","cod":200}'
setWeather(data);
function setWeather(data) {
//NOTE: only parse is needed
var json = JSON.parse(data);
alert(json['main']['temp']);
$('#temp').html(json['main']['temp']);
}
data is a String because of the single quotes , so if you called JSON.stringify(data) will add another double quotes to data , which means in order to convert data to JS object you will need to call JSON.parse(data) two times .
var obj ='{hello:1}'; //string
var json= JSON.stringify(obj);
console.log(json); // "\"{hello:1}\""
console.log(JSON.parse(json)); //"{hello:1}" => still a string
To get your code running correctly by converting data to object , just remove the JSON.stringify()
function setWeather(data) {
var json = JSON.parse(data); // remove JSON.stringify() => now json is object
alert(json['main']['temp']);
$('#temp').html(json['main']['temp']);
}
I have a string:
a = "{u'a':[u'123',u'321'], u'b':[u'456',u'654']}"
I want to convert this a to a json data.
How to do it?
I have tried JSON.parse(), but it will raise an error.
SyntaxError: Unexpected token u
That looks like Python literal syntax to me. Tell whoever wrote the Python portion to encode as JSON instead of just outputting the structure as a string.
In this particular case, you can just replace each u'x' with "x" and you'll have valid JSON:
var a = "{u'a':[u'123',u'321'], u'b':[u'456',u'654']}";
// Convert to JSON (May not work with other inputs!)
var json = a.replace(/u'((?:[^'\\]|\\.)*)'/g, function(a,str){
return '"' + str.replace(/\\'/g, '\'').replace(/"/g, '\\"') + '"';
});
// Parse the JSON into a Javascript object
var obj = JSON.parse(json);
Updated to work with some quotes in the object:
var a = "{u'a':[u'\\'123\\'',u'321'], u'b':[u'456\\\\',u'\"654\"']}";
Becomes:
{a:["'123'","321"], b:["456\",""654""]}
You need to change your input string to a valid JSON string.
I think this is what you wanted:
JSON.parse('{"a":["123","321"], "b":["456","654"]}')
The variables (keys / values ) are strings so need to be in quotes in order to be parsed as valid JSON.
// put quotes around the key / value pairs.
var a = "{\"u'a'\":[\"u'123'\",\"u'321'\"], \"u'b'\":[\"u'456'\",\"u'654'\"]}";
jQuery
a = $.parseJSON(a);
JSON is supposed to contain only strings.
a = "{u'a':[u'123',u'321'], u'b':[u'456',u'654']}"
Here I can only assume that u is a variable. Change it to this:
a = "{"+u+"'a':["+u+"'123',"+u+"'321'], "+u+"'b':["+u+"'456',"+u+"'654']}"
Hi i have the below json
{id:"12",data:"123556",details:{"name":"alan","age":"12"}}
i used the code below to parse
var chunk={id:"12",data:"123556",details:{"name":"alan","age":"12"}}
var jsonobj = JSON.parse(chunk);
console.log(jsonobj.details);
The output that i received is
{"name":"alan","age":"12"}
I need to get the individual strings from details say i should be able to parse and get the value of "name".I am stuck here any help will be much appreciated
If you already have an object, you don't need to parse it.
var chunk={id:"12",data:"123556",details:{"name":"alan","age":"12"}};
// chunk is already an object!
console.log(chunk.details);
// => {"name":"alan","age":"12"}
console.log(chunk.details.name);
//=> "alan"
You only use JSON.parse() when dealing with an actual json string. For example:
var str = '{"foo": "bar"}';
console.log(str.foo);
//=> undefined
// parse str into an object
var obj = JSON.parse(str);
console.log(obj.foo);
//=> "bar"
See json.org for more details
Since jsonobj has already been parsed as a JavaScript Object, jsonobj.details.name should be what you need.