Reading Values of JSON Message - javascript

I have been struggling with a few lines of Javascript code which should be straightforward. I have reduced my JSON String to the one found hereafter. The first alert in the code hereafter generates the following message:
{"list":[{"text":"Text1", "created_at":"Date1"},{"text":"Text2", "created_at":"Date2"}]}
However, the second alert generates the following error in IE:
Error: Unable to get value of the property '0': object is null or undefined
var data = "{\"list\":[{\"text\":\"Text1\", \"created_at\":\"Date1\"},{\"text\":\"Text2\", \"created_at\":\"Date2\"}]}";
alert(data);
alert(data.list[0].created_at);
Would anyone understand why I am receiving this error?

data is an ordinary string; it doesn't have any properties.
You want to parse the JSON in the string into a Javascript object:
var obj = JSON.parse(data);

You are using a string with Json formatting, but is not JSON itself.
You should use this:
var data = {"list":[{"text":"Text1", "created_at":"Date1"},{"text":"Text2", "created_at":"Date2"}]};
alert(data.list[0].created_at);
Or use:
var jsonData = JSON.parse(data);
alert(jsonData.list[0].created_at);

Related

Unable to correctly parse JSON object to a JavaScript Object

I have the following Json data that I am trying to transform to a Javascript object. Initially I tried using JSON.parse but it was saying an error so I figured the Json object was incorrectly configured. I did the following to resolve the issue.
The JSON is given in the following form:
{}{}{}...
But I wanted to change it to the following format:
[{},{},{}...]
So I did the following
var news = fs.readFileSync("data.json", "utf8")
//Stringified data
var newsdata = JSON.stringify(news)
// add comma in between
data = newsdata.replace('}{', '},{')
// The resulting data doesn't have a comma between individual objects
parsedNews = JSON.parse(data)
The str.replace() command isn't changing it to a desired format. How should I resolve the issue?

Get JavaScript object from database

I've a table in a SQL DB in which I store a JavaScript object like this:
{content: ['First paragraph','second paragraph']}
I get it from DB and try to pass to a function which needs an object formatted like it:
this._schedaService.getObjectFromDBToPrintPdf().subscribe(data => {
pdfMake.createPdf(data).download('tempPdf.pdf');
});
The problem is that data is always a string.
I've tried JSON.parse(data) but (obviously) doesn't work.
If I write
cont temp = {content: ['First paragraph','second paragraph']};
it works.
Does anyone have a good idea?
If you use the JSON.parse JavaScript function, e.g.
var data = JSON.parse("{content: ['First paragraph','second paragraph']}");
you will receive the following error:
Uncaught SyntaxError: Unexpected token c in JSON at position 1
because your input string does not have a valid JSON object syntax.
Your input string should have this format:
'{"content": ["First paragraph","second paragraph"]}'
I solved it in a tricky way: since JSON.parse is a specific type of the eval function, I just focused on JSON. The only solution (that I've found 'till now) is:
var str = "{content: ['First paragraph','second paragraph']}";
var obj = eval("(" + str + ")");
N.B. typeof(obj) returns
object
Here is an useful link.

Parse JSON Data from a String variable and convert it to objects in a $scope.variable

I have a string variable containg JSON data as below.
var jsonstring = [{"latitude":"51.5263","longitude":"-0.120285","altitude":"","device":"123","rating":"5","region":"Europe","customer":"","time":"1-2 Weeks","error":"Error 1","application":"Phone","age":"< 1 Year"},
{"latitude":"27.58","longitude":"23.43","altitude":"","device":"Asc 140","rating":"4","region":"Africa","customer":"","time":"< 1 Week","error":"Error 1","application":"PCB","age":"1-3 Years"},
{"latitude":"39.55","longitude":"116.25","altitude":"","device":"CVB","rating":"4","region":"China","customer":"","time":"1-2 Weeks","error":"Error 2","application":"Sorting","age":"3-5 Years"}]
I want to get this string and convert it to an array of objects (which would be a $scope.variable) so that i can be able to access each object individually.
I tried to use the JSON.parse() but it gets the entire string into one object instead of multiple objects.
Kindly help me with this.
You've to parse the entire string with JSON.parse.
Each object in the array can then be reached like any other array, e.g. myArray[index], myArray.map() / myArray.forEach() etc
[{"latitude":"51.5263","longitude":"-0.120285","altitude":"","device":"123","rating":"5","region":"Europe","customer":"","time":"1-2 Weeks","error":"Error 1","application":"Phone","age":"< 1 Year"},
{"latitude":"27.58","longitude":"23.43","altitude":"","device":"Asc 140","rating":"4","region":"Africa","customer":"","time":"< 1 Week","error":"Error 1","application":"PCB","age":"1-3 Years"},
{"latitude":"39.55","longitude":"116.25","altitude":"","device":"CVB","rating":"4","region":"China","customer":"","time":"1-2 Weeks","error":"Error 2","application":"Sorting","age":"3-5 Years"}]
This is an array object.It's not a string object.
You can try again like this:
var jsonString = "[]";
var json = JSON.parse(jsonString);
var jsonstring = '[{"latitude":"51.5263","longitude":"-0.120285","altitude":"","device":"123","rating":"5","region":"Europe","customer":"","time":"1-2 Weeks","error":"Error 1","application":"Phone","age":"< 1 Year"}, {"latitude":"27.58","longitude":"23.43","altitude":"","device":"Asc 140","rating":"4","region":"Africa","customer":"","time":"< 1 Week","error":"Error 1","application":"PCB","age":"1-3 Years"}, {"latitude":"39.55","longitude":"116.25","altitude":"","device":"CVB","rating":"4","region":"China","customer":"","time":"1-2 Weeks","error":"Error 2","application":"Sorting","age":"3-5 Years"}]';
$scope.variable = JSON.parse(jsonstring);
The JSON.parse() method parses a string as JSON.
Code in your question, shows that you are trying to parse a JS object and not a string.
In the following example, you get an error if you try to parse a JS object.
var jsonstring = [{},{}];
JSON.parse(jsonstring); // ERROR Uncaught SyntaxError: Unexpected token o
The following works instead (please note jsonstring is a string and not an object here):
var jsonstring = '[{},{}]';
JSON.parse(jsonstring); // OK

How to get json value in js code?

I have a json code and i want get json value units_num in alert jQuery. How can don it?
My json code:
[{"id":"11","name":"hiih","units_num":00}]
I tried as in js code: http://jsfiddle.net/Wj8ZL/
var obj = $.parseJSON('[{"id":"11","name":"hiih","units_num":00}]');
alert(obj['units_num']); // This don't work
var t = JSON.parse('[{"id":"11","name":"hiih","units_num":00}]');
alert(t['units_num']) // This don't work
Your json contains an array of objects, even if there is only one in there. So you need to access that first object in the array
var obj = $.parseJSON('[{"id":"11","name":"hiih","units_num":"00"}]');
alert(obj[0]['units_num']);
#TravisJ gave a big part of the issue, the other one being quite easy to spot if you read the error log:
"units_num":00
is not valid. It should read
"units_num":0

converting simple JSON string into JSON object

Code:
var jsonTest = {};
var testjson = ["xxxx.jpg","xxx.jpg","xxx.jpg"];
jsonTest = JSON.parse(testjson);
Error message:
Unable to parse JSON string.
However, when I test this in a JSON validator, it tells me that it is correct JSON.
testjson is already a valid javascript array, there is no need to parse it.

Categories

Resources