javascript split and JSON.parse - javascript

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(',');

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

javascript get nested array elements

in javascript how do I get individual elements out of this array?
http://pastebin.com/n8yrnCpf
I need to loop through it and format the data
how would I get array[0][1][1], for instance
and perhaps there is some json script for doing it quickly
Json comes from J ava S cript O bject N otation. It's a javascript-compatible format, so you can loop through it, and access it as you need. In other words, you do can get array[0][1][1].
If what you're asking for is how can you receive a JSON in a string and convert it to an "usable" JavaScript variable, you can do that this way:
var json_string = "[[['whatever','and'],['more','whatever']]]"
var parsed_json = JSON.parse (json_string)
console.log (parsed_json[0][0])
Or, if you use old browsers (IE7 and so), you can use JQuery and its elder-safe function parseJSON:
var json_string = "[[['whatever','and'],['more','whatever']]]"
var parsed_json = $.parseJSON (json_string)
console.log (parsed_json[0][0])

Trying to convert multi level javascript array to json, with json2 script

I am using the following script to help me convert javascript arrays to json strings: https://github.com/douglascrockford/JSON-js/blob/master/json2.js
How come this works:
var data = [];
data[1] = [];
data[1].push('some info');
data[1].push('some more info');
json_data = JSON.stringify(data);
alert(json_data);
And this does not (returns a blank):
var data = [];
data['abc'] = [];
data['abc'].push('some info');
data['abc'].push('some more info');
json_data = JSON.stringify(data);
alert(json_data);
I want to convert multi-dimensional javascript arrays, but it seems I cannot use stringify() if I name my array keys?
JSON arrays are integer-indexed only.
You can change your first line to use {} as in http://jsfiddle.net/5YXNk/, which is the best you can do here.
Check the array syntax at http://json.org/ -- note arrays contain values only, which will be implicitly indexed by non-negative integers. That's just the way it is.
There is no such thing as an associative array in Javascript. You're going to have to use an object if you want to use string "keys".

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