javascript convert string to data - javascript

I have JavaScript code below.
var data = "[{"PR_ID":23096,"P_ID":23014},{"PR_ID":33232,"P_ID":23014},{"PR_ID":33308,"P_ID":23014},{"PR_ID":33309,"P_ID":23014}]";
I need convert the string to an data by delete the "" surrounding the array stored as "data" in JavaScript so after convert it suppose like below:
var data = [{"PR_ID":23096,"P_ID":23014},{"PR_ID":33232,"P_ID":23014},{"PR_ID":33308,"P_ID":23014},{"PR_ID":33309,"P_ID":23014}];
How to make the convert?

To convert a JSON object to Javascript object use:
var data = '[{"PR_ID":23096,"P_ID":23014},{"PR_ID":33232,"P_ID":23014},{"PR_ID":33308,"P_ID":23014},{"PR_ID":33309,"P_ID":23014}]';
JSON.parse(data);
But first change the double quote to single quote, otherwise the JSON object wont be a valid JSON.
After this you can walk the array in the following way:
var jsonParsed = JSON.parse(data);
for(var val in jsonParsed) {
if(jsonParsed.hasOwnProperty(val)) {
// do something with the values
}
}

Related

Convert array string to array for mapping data

Here is my problem
const data = "[\"https://i.imgur.com/PAYXC2n.jpg\",\"https://i.imgur.com/bEfjjxA.jpg\"]";
I want to convert this string to array,
expected result will be :
res =["https://i.imgur.com/PAYXC2n.jpg","https://i.imgur.com/bEfjjxA.jpg"]
I use it for mapping data in React JS project, so i need to convert this string to array.
Just parse it from JSON:
const
data = "[\"https://i.imgur.com/PAYXC2n.jpg\",\"https://i.imgur.com/bEfjjxA.jpg\"]",
parsed = JSON.parse(data);
console.log(parsed);
Do it:
const dataArr = JSON.parse(data);. This will parse as to object, which is your array (With out "")

Parsing JSON under Array object

I have a simple JSON string, encapsulated in an array created using JSONArray and JSONObject form org.json in Java.
var outObjA = [{"LoginTime":"2018-02-14 08:51:48.0","User":"f00dl3","RemoteIP":"127.0.0.1"}];
I am trying to parse this in JavaScript. First I iterate over the array encapsulating the data using an `i" counter:
for(var i = 0; i < outObjA.length; i++) {
var jsonData = JSON.parse(outObjA[i]);
console.log(jsonData);
}
When I attempt to parse the JSON, I get an error:
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
I built a try/catch into it and it returns an object:
for (var i = 0; i < outObjA.length; i++) {
var jsonData = null;
try {
jsonData = JSON.parse(outObjA[i]);
} catch (e) {
jsonData = outObjA[i];
}
console.log(jsonData);
}
Returned:
{
"LoginTime": "2018-02-14 08:51:48.0",
"User": "f00dl3",
"RemoteIP": "127.0.0.1"
}
This is valid JSON, is it not?
That's not a JSON string, it's a JavaScript array. To make it a JSON string, surround it with apostrophes, then you can parse it, and finally loop through it:
var outObjA = '[{"LoginTime":"2018-02-14 08:51:48.0","User":"f00dl3","RemoteIP":"127.0.0.1"}]';
var outObjA = JSON.parse(outObjA);
for (var i = 0; i < outObjA.length; i++) {
var jsonData = outObjA[i];
console.log(jsonData);
}
Or better, you can loop through it directly without parsing:
var outObjA = [{"LoginTime": "2018-02-14 08:51:48.0", "User": "f00dl3", "RemoteIP": "127.0.0.1"}];
for (var i = 0; i < outObjA.length; i++) {
var jsonData = outObjA[i];
console.log(jsonData);
}
This line is not necessary.
for(var i = 0; i < outObjA.length; i++) {
var jsonData = JSON.parse(outObjA[i]);
console.log(jsonData);
}
Because outObjA is a array type not json,it does not need parsing simply retrieve it and display it.
The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned, source.
To expand further take this example from Mozilla ,
var json = '{"result":true, "count":42}';
The reason why this needs parsing is because its a string type, the JSON.parse converts that string into a JSON object, thus making it accessible. like this,
obj = JSON.parse(json);
console.log(obj.count);
// expected output: 42
console.log(obj.result);
// expected output: tru
The only way your code would work is if you did this.
var outObjA = ['{"LoginTime":"2018-02-14 08:51:48.0","User":"f00dl3","RemoteIP":"127.0.0.1"}'];
This way the element at position zero is a string, not a JSON object.
To conclude, strings are not JSON.
JSON objects are surrounded by curly braces {}.
JSON objects are written in key/value pairs.
Keys must be strings, and values must be a valid JSON data type
(string, number, object, array, boolean or null).
Keys and values are separated by a colon.
Each key/value pair is separated by a comma.
you do not need parse for it is already json
you might use instead
var jsonData = outObjA[i];
console.log(jsonData['User']); // or any other key

Fetch localstorage value in array

I am saving value in localstorage as shown below
key = profskill , value = "a,b,c"
In my test.ts file, I have declared array but I am unable to fetch the result in it. Code shown below:
getskills: Array<string> = [];
this.getskills = localStorage.getItem("profskill");
but this is giving error:
Type 'string' is not assignable to type 'string[]'
I want to fetch value like this:
console.log(this.getskills[0]);
The LocalStorage can only store strings, not objects or arrays. If you try to store an array, it will automatically be converted to a string. You need to parse it back to an array :
JSON.parse( localStorage.getItem("profskill") )
Since, you want the comma separated value to be represented as a array of strings for this.getskills use split on the value of the localStorage
Here is a sample example
//say we get the value 'a,b,c' from localStorage into the temp variable
//var temp = localStorage.getItem(profskill);
var temp= 'a,b,c';
this.getskills = temp.split(',');
console.log(this.getskills[0]);
localStorage only supports strings. Use JSON.stringify() to set the data in storage and JSON.parse() to get the data from storage and then use split(",") to split the comma separated data.
var obj = "a,b,c";
localStorage.setItem("profskill", JSON.stringify(obj));
var getskills = [];
getskills = JSON.parse(localStorage.getItem("profskill")).split(",");
console.log(getskills[0]);
First get the data from the LocalStorage:
var DataTableValue = JSON.parse(localStorage.getItem('dataTableValue'));
Then, store in an Array:
var tempArray = new Array();
for (var i = 0; i < DTarray.length; i++) {
tempArray.push(DTarray[i]);
}
All data will be stored in the variable tempArray.

splitting json array in javascript not working

I am getting the response from ajax as json:
{"checkin_date":["2017-05-11","2017-05-18","2017-05-23","2017-05-25"]}
I need to separate these values in javascript like 2017-05-11, 2017-05-18, etc.
I tried split function in javascript but it failed. How do I achieve it?
I need the dates separately in a loop.
Parse the JSON string using JSON.parse method and get the property which holds the array.
var dates = JSON.parse(respose_data).checkin_date
// or
var dates = JSON.parse(respose_data)['checkin_date']
If it's an object then directly access the property.
var dates = respose_data.checkin_date
// or
var dates = respose_data['checkin_date']
UPDATE : And now iterate over the array using Array#forEach or a simple for loop.
dates.forEach(function(v){
console.log(v);
})
// or
for(var i = 0;dates.length < i; i++){
console.log(dates[i]);
})
You just use method parse of JSON. After that, you receive array value for property "checkin_date". Just use it as normal array. See code below:
var json = '{"checkin_date":["2017-05-11","2017-05-18","2017-05-23","2017-05-25"]}';
var result = JSON.parse(json);
var checkin_date = result['checkin_date'];
for(var i=0; i<checkin_date.length; i++){
console.log(checkin_date[i]);
}
You can do a simple solution using arrow function:
const json = {"checkin_date":["2017-05-11","2017-05-18","2017-05-23","2017-05-25"]}
json.checkin_date.map((date) => date)
If you need it on pre-ES6 JavaScript, just do it like:
var json = {"checkin_date":["2017-05-11","2017-05-18","2017-05-23","2017-05-25"]}
json.checkin_date.map(function(date) { return date })
Both ways you will have returned all the dates from the loop.
You could:
Parse content of your request to a JavaScript object using JSON.parse().
Take property checkin_date which contains an Array with the list of dates.
Loop the Array and do whatever you need which each date.
let respose_data = '{"checkin_date":["2017-05-11","2017-05-18","2017-05-23","2017-05-25"]}';
let dates = JSON.parse(respose_data).checkin_date;
dates.forEach(date=> console.log(date))
More info on JSON.parse()
If you need to loop through each value as a date, you first need to convert the values. Take a look:
var dates = {"checkin_date":["2017-05-11","2017-05-18","2017-05-23","2017-05-25"]};
dates
.checkin_date
.map(date => new Date(date)) // here you convert the string dates to values of type Date
.forEach(date => console.log(date)) // here you loop through every Date and do whatever you want, in this case I just logged the output.

Convert almost JSON string to JSON object Javascript

I have an string object like the following:
CustomData {
href: 'https://api.stormpath.com/v1/accounts/fdsq/customData',
createdAt: '2017-02-12T21:06:34.086Z',
modifiedAt: '2017-02-14T20:36:45.879Z',
ethereum_contract_address: '485dsq41g52fdsqqds',
ethereum_provider: 'proqxy53fdsq.yoicsfdsqfdsq.net:31gky6736' }
I am trying to convert this string to a JSON object that I can then use properly. But i can't seem to convert this to a simple string that I could then substring and then parse to JSON.
Here is what i have attempted:
var rawString = req.user.customData;
console.log(rawString);
var stringJson = String(rawString).substring(0, 11);
console.log(stringJson.toString());
var customData = JSON.parse(stringJson);
console.log(customData);
I unfortunatly get stcuk on the JSON.parse, it seems like the string String(rawString) does not actually convert it to a string but only retruns [object Object].
You should use
JSON.stringify(jsonData);
then just simply parse
JSON.parse(jsonString)
You need JSON.stringigy(obj); to get a JSON-object of your data. Heres the code:
var customData = {
href: 'https://api.stormpath.com/v1/accounts/fdsq/customData',
createdAt: '2017-02-12T21:06:34.086Z',
modifiedAt: '2017-02-14T20:36:45.879Z',
ethereum_contract_address: '485dsq41g52fdsqqds',
ethereum_provider: 'proqxy53fdsq.yoicsfdsqfdsq.net:31gky6736'
}
console.log(customData);
var stringJson = JSON.stringify(customData);
console.log(stringJson);
var customData = JSON.parse(stringJson);
console.log(customData);
CustomData is a JSON: It contains keys and values. JSON stands for JavaScript Object Notation. You confuse JSON with JSON string. From the former you can achieve the latter via
var JSONString = JSON.stringify(CustomData);
You can parse it via
JSON.parse(JSONString);
However, since your object is already a JSON, you should be able to use it properly, whatever that means in your scenario.

Categories

Resources