Parse object to JSON - javascript

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.

Related

Remove multiple square brackets using replace() - javascript

I have a response from the server that is like this:
users: ["beautykarttworld","sbdanwar","haiirfavs","show__tanz","kinjal_suhagiya_9999","_adultmafia_"]
It's a string not an array like it appear, since I need an array to work on, how I can remove the square backets and then the commas to obtain a normal array?
I've tried in this way:
var data = ["beautykarttworld","sbdanwar","haiirfavs","show__tanz","kinjal_suhagiya_9999","_adultmafia_"]
data.replace('[', '').replace(']', '').split(',');
but chaining two .replace() functions and a split() isn't the best solution. Can anyone halp me?
In your example data is an array.
However, if data was a string you would convert it to an array like this:
var arr = JSON.parse(data);
In short,
Here you have provided data in normal string formate not in JSON string formate
var data = 'users: ["beautykarttworld","sbdanwar","haiirfavs","show__tanz","kinjal_suhagiya_9999","_adultmafia_"]'
var squareBracketData = data.substr(data.indexOf("["))
var array = JSON.parse(squareBracketData)
console.log(array)
Some personal advice, Try to send JSON stringify data from the
server so it will make your life easy
Example:
var users =["beautykarttworld","sbdanwar","haiirfavs","show__tanz","kinjal_suhagiya_9999","_adultmafia_"]
// Stringify data
var data = JSON.stringify({users})
console.log("Data")
console.log(data)
// retrieve data from string
var parsedData = JSON.parse(data)
var parsedUsers = parsedData.users
console.log("parsedUsers")
console.log(parsedUsers)

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

NODEJS unable to send json formatted response?

I am trying to send json response from my nodejs application to the client. However, the response does not seem to be in the right format can someone point me what is it that i am doing wrong ?
Below is subset of my code
var insertdata = "create-fail";
var updatedata = "update-fail";
var deletedata = "delete-fail";
insertdata = "{ create:pass ,";
updatedata = "update:pass ,";
deletedata = "delete:pass }";
var jsondata = insertdata+updatedata+deletedata;
res.send(JSON.stringify(jsondata));
Output browser:
"{ create:pass ,update:pass ,delete:pass }"
JSON.stringify should receive an object, not a string.
var jsondata = {'create':'pass', 'update':'pass', 'delete':'pass'};
res.send(JSON.stringify(jsondata));
This is an object:
object = { hello: 1 }
This is a string:
string = "{ 'hello': 1 }"
The string looks similar to the object, because its format is JSON (Javascript Object Notation), which is inspired in the way object is declared above.
Objects can't travel across the internet, but strings can. You can go from object to string using JSON.stringify():
string = JSON.stringify(object)
When you receive it on the other side, go back using JSON.parse():
object = JSON.parse(string)
jsondata is a string - and then you're stingifying it. If you're using jQuery, use $.parseJSON or use the json2 library.

Javascript JSON.parse or directly access

When we can read a property directly from string:
var data = {"id":1,"name":"abc","address":{"streetName":"cde","streetId":2}};
console.log(data.address.streetName); // cde
Why do people use JSON.parse:
var obj = JSON.parse(data);
console.log(obj.address.streetName); // cde
It is not a string, but Javascript object. String is given below
var data = '{"id":1,"name":"abc","address":{"streetName":"cde","streetId":2}}';
to make it object we use JSON.parse
var obj = JSON.parse(data);
console.log(obj.address.streetName); // cde
In your first example, data is an object, but in your second example, data is a JSON string.
That's a major difference. You could call eval(data) to parse a JSON string, but that's very unsafe.
JSON.parse() expects a string. More specifically, a string with a JSON-encoded piece of data.
If it's applied to an object then it's an error, the source of which is probably the common confusion that seems to exist between JavaScript objects and the JSON format.

javascript split and JSON.parse

I want to parse array in JSON format using javascript. I have written following code.
var data = "abc, xyz, pqr";
var data_array = data.split(',');
var data_parsed = JSON.parse(data_array);
alert(data_parsed);
It gives me the error of JSON.parse
I have no idea how to resolve this javascript error.
You don't have any JSON, so don't use JSON.parse. Once you split you already have an array whose elements could be used directly:
var data = "abc, xyz, pqr";
var data_array = data.split(',');
alert(data_array[0]);
and if you want to convert this array to a JSON string you could do this:
var json = JSON.stringify(data_array);
alert(json);
That's because "abc, xyz, pqr" isn't valid JSON. Plus, JSON.parse() is meant to parse JSON strings, not arrays. What are you trying to do, perhaps we can better assist.
This is actually a convenient short cut to json processing if you only need a smaller set of variables.
PHP:
return $var1 .','. $var2 .',some_string_value.';
Javascript:
var myReturnArray = returnValue.split(',');

Categories

Resources