converting simple JSON string into JSON object - javascript

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.

Related

Get jqGrid ajax Nested Array of Json string in C# by Newtonsoft Json

I'm trying to parse Json string and collect array values present inside it.
{"_search":true,"nd":1492064211841,"rows":30,"page":1,"sidx":"","sord":"asc","filters":"{\"groupOp\":\"OR\",\"rules\":[{\"field\":\"Emp_ID\",\"op\":\"cn\",\"data\":\"ASAS\"},{\"field\":\"Name\",\"op\":\"cn\",\"data\":\"ASAS\"},{\"field\":\"Designation\",\"op\":\"cn\",\"data\":\"ASAS\"},{\"field\":\"City\",\"op\":\"cn\",\"data\":\"ASAS\"},{\"field\":\"State\",\"op\":\"cn\",\"data\":\"ASAS\"},{\"field\":\"Country\",\"op\":\"cn\",\"data\":\"ASAS\"}]}"}
PS: Above string is coming from jqGrid Ajax to the WebMethod in C#.
I'm not getting success on getting filters->rules[0]->data
What I've tried :
dynamic jObj = JObject.Parse(postData);
var data = jObj.filters.rules[0].data;
getting error: 'Newtonsoft.Json.Linq.JValue' does not contain a definition for 'rules'.
dynamic jObj = JObject.Parse(postData);
var filters = jObj.filters; //Sucess: getting filters here
var rules1 = filters["rules"]; //Error: 'Newtonsoft.Json.Linq.JValue' does not contain a definition for 'rules'.
var rules2 = filters.rules; //Error: 'Newtonsoft.Json.Linq.JValue' does not contain a definition for 'rules'.
How to get value inside filters->rules AND filters->rules[0]->data ?
You must parse the internal object like this :
var obj = "{\"_search\":true,\"nd\":1492064211841,\"rows\":30,\"page\":1,\"sidx\":\"\",\"sord\":\"asc\",\"filters\":\"{\\\"groupOp\\\":\\\"OR\\\",\\\"rules\\\":[{\\\"field\\\":\\\"Emp_ID\\\",\\\"op\\\":\\\"cn\\\",\\\"data\\\":\\\"ASAS\\\"},{\\\"field\\\":\\\"Name\\\",\\\"op\\\":\\\"cn\\\",\\\"data\\\":\\\"ASAS\\\"},{\\\"field\\\":\\\"Designation\\\",\\\"op\\\":\\\"cn\\\",\\\"data\\\":\\\"ASAS\\\"},{\\\"field\\\":\\\"City\\\",\\\"op\\\":\\\"cn\\\",\\\"data\\\":\\\"ASAS\\\"},{\\\"field\\\":\\\"State\\\",\\\"op\\\":\\\"cn\\\",\\\"data\\\":\\\"ASAS\\\"},{\\\"field\\\":\\\"Country\\\",\\\"op\\\":\\\"cn\\\",\\\"data\\\":\\\"ASAS\\\"}]}\"}";
dynamic jObj = JObject.Parse(obj);
var data = JObject.Parse(jObj.filters.Value);
var test = data.rules;
Console.WriteLine(data);
Console.ReadLine();
I don't have the knowledge about C# but I have tried into it on JavaScript
In your json, in filters field not is'nt proper json it is string
I have do this on javascript might it will help's you
var a = {"_search":true,"nd":1492064211841,"rows":30,"page":1,"sidx":"","sord":"asc","filters":"{\"groupOp\":\"OR\",\"rules\":[{\"field\":\"Emp_ID\",\"op\":\"cn\",\"data\":\"ASAS\"},{\"field\":\"Name\",\"op\":\"cn\",\"data\":\"ASAS\"},{\"field\":\"Designation\",\"op\":\"cn\",\"data\":\"ASAS\"},{\"field\":\"City\",\"op\":\"cn\",\"data\":\"ASAS\"},{\"field\":\"State\",\"op\":\"cn\",\"data\":\"ASAS\"},{\"field\":\"Country\",\"op\":\"cn\",\"data\":\"ASAS\"}]}"}
console.log(a.filters)
it is returns
"{"groupOp":"OR","rules":[{"field":"Emp_ID","op":"cn","data":"ASAS"},{"field":"Name","op":"cn","data":"ASAS"},{"field":"Designation","op":"cn","data":"ASAS"}
and it is string now i'm again parse into it on JSON
b = JSON.parse(a.filters)
console.log(b.rules)
now it returns rules objects

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

Parse json encoded array and fetch values

How to parse these JSon array am getting from json_encode(arr), the output is:
[{"id":"44","data":"[[10],[27],[13]]","_types":"ff"}, {"id":"44","data":"[[140],[327],[213]]","_types":"44f"}]
I need to iterate this using java script and fetch each values.
Am getting an error, Unexpected token.
You are getting a string, you simply need to do JSON.parse
var str = '[{"id":"44","data":"[[10],[27],[13]]","_types":"ff"}, {"id":"44","data":"[[140],[327],[213]]","_types":"44f"}]';
var obj = JSON.parse( str );
alert( obj[0].id );
You are getting array of java script object,i think you don't need to parse this.Just iterate this and fetch the result like below.
var q = [{"id":"44","data":"[[10],[27],[13]]","_types":"ff"}, {"id":"44","data":"[[140],[327],[213]]","_types":"44f"}];
q.forEach(function(i){console.log(i.id)});

Reading Values of JSON Message

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);

Parse object to JSON

I have some web services that receive JSON data send by jquery method.
But I need to edit the object before send this data. Is there any way to parse a JSON object to a simple object in javascript, modify it and then parse it again to JSON. or maybe update this JSON object without parse it?
To go from a JSON string to a JavaScript object: JSON.parse, or $.parseJSON if you're using jQuery and concerned about compatibility with older browsers.
To go from a JavaScript object to a JSON string: JSON.stringify.
If I've already do this var myData = JSON.stringify({ oJson:{data1 :1}}); and then I want to update that information setting data1 = 2, what is the best way to do this?
var myData = JSON.stringify({ oJson:{data1 :1}});
// later...
parsedData = JSON.parse(myData);
parsedData.oJson.data1 = 2;
myData = JSON.stringify(parsedData);
Even better though, if you save a reference to the object before stringifying it, you don't have to parse the JSON at all:
var obj = { oJson:{data1 :1}};
var myData = JSON.stringify(obj);
// later...
obj.oJson.data1 = 2;
myData = JSON.stringify(obj);
var parsed = JSON.parse('{"a": 1}');
parsed.b = 2;
var string = JSON.stringify(parsed);
//string is: '{"a":1,"b":2}'
I think something like the following should work...
//Convert your JSON object into a JavaScript object
var myObject = JSON.parse(json);
//You can then manipulate the JavaScript object like any other
myObject.SomeValue = "new";
//Then you can convert back to a JSON formatted string
json = JSON.stringify(myObject);
As JSON is an JavaScript object you can simply manipulate it with JavaScript.
You could do something like this to get a javascript object:
var jsObject = JSON.parse(jsonString);
Then you could modify jsObject and turn it back into a JSON string with JSON.stringify.
This page has more information on it.

Categories

Resources