Unwanted backslash in json when stored in localstorage - javascript

I am storing a json first in localstorage and then again storing it in final json but I am getting extra backslash in my final json. My code is:
<!DOCTYPE html>
<html>
<body>
<script>
var mi = [{
"name": "Alex",
"address": "abc"
},
{
"name": "George",
"address": "efg"
}
]
localStorage.setItem("myData", JSON.stringify(mi))
var FinalJson = {
"Collected values" : localStorage.getItem("myData"),
"Place" : "washington"
};
document.write(JSON.stringify(FinalJson));
</script>
</body>
</html>
Output I am getting is:
{"Collected values":"[{\"name\":\"Alex\",\"address\":\"abc\"} {\"name\":\"George\",\"address\":\"efg\"}]","Place":"washington"}
Where am i going wrong that I am getting this extra backslash. How can I remove the extra backslashes? P.S. I don't want to directly store the variable mi in my FinalJson, as it contains some more complicated values which I have removed here for simplicity.

It's stringified twice
var FinalJson = {
"Collected values" : JSON.parse(localStorage.getItem("myData")),
"Place" : "washington"
};
http://jsfiddle.net/Kh5Br/

var mi = [{
"name": "Alex",
"address": "abc"
},
{
"name": "George",
"address": "efg"
}
];
localStorage.setItem("myData", JSON.stringify(mi))
var tes = JSON.parse(localStorage.getItem("myData")); //It was "work". I thougt you missed that
var FinalJson = {
"Collected values" : tes,
"Place" : "washington"
};
document.write(JSON.stringify(FinalJson));
document.write(tes);

Related

Script that stores multiple values from JSON dictionary into array

I have over 1000s of dictionaries in JSON after an API request. How do create a script that iterates over all dictionaries and stores the values of one of the key-value pairs?
example
},"testData"
{
"testJSON": "test",
"phone": null,
"address: "122 main st"
}, "testData1"
{
"testJSON": "test1",
"phone": null,
"address: "123 main st"
},
For example, how do I get the "address" field of every single JSON dictionary?
You need to first parse your json, like this:
var json = JSON.parse(jsonString);
then you could iterate your json keys and do something with the root values, like such:
for(var el in json)
{
console.log(json[el]) // will log every root element
console.log(json[el].phone) // will log phone of each element
}
example fiddle: https://jsfiddle.net/1ky6dzen/
In python this can be done like this:
data = [{
"testJSON": "test",
"phone": null,
"address: "122 main st"
}, "testData1"
{
"testJSON": "test1",
"phone": null,
"address: "123 main st"
}]
my_array = []
for obj in data:
my_array.append(obj['address'])
print(my_array)
Hope this is what you were after :)
Use forEach loop to iterate over the keys of the object
var a={"testData":
{
"testJSON": "test",
"phone": null,
"address": "122 main st"
}, "testData1":
{
"testJSON": "test1",
"phone": null,
"address": "123 main st"
}};
Object.keys(a).forEach(e=>console.log(a[e].address))

Swap rows/indexes within a JavaScript array using AngularJS

I have a custom directive that is holding an array of JavaScript objects.
The object is a little complex and lengthy but I will display something similar to point out my problem:
A JSON.stringify of this displays the following:
[
{
"Id": 1,
"Name": "John Doe",
"EMail": "john#doe.com"
},
{
"Id": 2,
"Name": "Jim Doe",
"EMail": "jim#doe.com"
},
{
"Id": 3,
"Name": "Jeff Doe",
"EMail": "jeff#doe.com"
}
]
I am further using ng-repeat to display the values in a tabular form on my HTML.
The values are coming from an API call that fetches them from a database.
I want to swap - say the entire Object with Id 1 with the entire Object with Id 3 so that during my tabular display I can see Id 3 object details first and Id 1 object details last, without breaking any functionality.
What would be the best possible solution to do this within the frontend itself?
How about just swapping them using a temp variable?
var arr = [{"Id":1,"Name":"John Doe","EMail":"john#doe.com"},
{"Id":2,"Name":"Jim Doe","EMail":"jim#doe.com"},
{"Id":3,"Name":"Jeff Doe","EMail":"jeff#doe.com"}]
var tmpObj = arr[0];
arr[0] = arr[2];
arr[2] = tmpObj;
If you want to reverse the array, use Array.prototype.reverse()
var app = angular.module("myApp", []);
app.controller("myController", function($scope) {
var arr = [
{
"Id": 1,
"Name": "John Doe",
"EMail": "john#doe.com"
},
{
"Id": 2,
"Name": "Jim Doe",
"EMail": "jim#doe.com"
},
{
"Id": 3,
"Name": "Jeff Doe",
"EMail": "jeff#doe.com"
}
];
$scope.array = arr.reverse();
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="myController">
<div ng-repeat="item in array">
{{item.Id}} - {{item.Name}} - {{item.EMail}}
</div>
</div>
</div>

Can't retrieve data from JSON in Javascript. The json is passed from php

I have a problem and i search for a solution, but i can't find it. I have this Json:
[
{
"name": "Pippo (74)",
"price": "1",
"latitudine": "10.32562",
"longitudine": "44.8003686"
},
{
"name": "pluto",
"price": "2",
"latitudine": "10.32562",
"longitudine": "44.8003686"
}
]
I want retrieve data from the Json (named msg):
num = msg.length;
document.write (num);
document.write (msg[0].name);
But it don't work! Can you help me?
You might use this parse json.
http://api.jquery.com/jquery.parsejson/
var output = jQuery.parseJSON( '[
{
"name": "Pippo (74)",
"price": "1",
"latitudine": "10.32562",
"longitudine": "44.8003686"
},
{
"name": "pluto",
"price": "2",
"latitudine": "10.32562",
"longitudine": "44.8003686"
}]' );
var list = output.data;
$.each(list,function(i,item){
console.log(item.name);
});
you can use var parsedMsg = JSON.parse(msg); to transform to a pure JS object. Then run your script. You also have a typo in 'length'
A shot in the dark here, but guessing your JSON needs to be parsed:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
var parsedMsg = JSON.parse(msg);
then you can do whatever you like with the data:
num = parsedMsg.length;
console.log(num);
console.log(parsedMsg[0].name);

How to Get key value from parseJson()

I have a case that is how to find the value of a key that is in sekrip as follows:
JSON.parse({
"data": [
{
"id_user": "351023",
"name": "",
"age": "29",
"link": "http://domain.com"
}
]
});
The above data was obtained from:
<script type='text/javascript' src='http://domain.com/target.php'></script>
I want to get the value of the key "id_user", anyone can help me?
Thanks before.
Several issues here. Firstly, the method you're looking for is JSON.parse(), not parseJSON. Secondly, what you're providing to that function is already an object, not a JSON string, therefore it doesn't need to be deserialised as you can access it as you would any normal object:
var obj = {
"data": [{
"id_user": "351023",
"name": "",
"age": "29",
"link": "http://domain.com"
}]
}
console.log(obj.data[0].id_user);
First its JSON.parse. Second it needs to be a JSON string.
Fiddle: http://jsfiddle.net/5m5qs1x4/
var jsonData = JSON.parse('{"data": [{"id_user": "351023","name": "","age": "29","link": "http://domain.com"}]}');
document.getElementById('test').textContent = jsonData.data[0].id_user;
You need to parse JSON string and than, access to keys/index
var data = JSON.parse("{\"data\": [{ \"id_user\": \"351023\",\"name\": \"\",\"age\": \"29\",\"link\": \"http://domain.com\"}]}");
document.write(data["data"][0]["id_user"]);

Json in sessionStorage with array of objects

Hi all I am creating a Json and adding it to Sessionstorage as follows
<script type="text/javascript">
function addMoreProducts() {
if (sessionStorage.getItem("empData") === null) {
var empInformation = {
"employees": [
{ "firstName": "John", "lastName": "Doe" },
{ "firstName": "Anna", "lastName": "Smith" },
{ "firstName": "Peter", "lastName": "Jones" }
]
}
var x = JSON.stringify(empInformation);
sessionStorage.setItem("empData", x);
}
else {
if (sessionStorage.getItem("empData") != null) {
var empInformation = {
"employees": [
{ "firstName": "John1", "lastName": "Doe1" },
{ "firstName": "Anna1", "lastName": "Smith1" },
{ "firstName": "Peter1", "lastName": "Jones1" }
]
}
var v = sessionStorage.getItem("empData").toString();
var jParse = JSON.stringify(v);
var jparse1 = JSON.stringify(empInformation);
var arrayOfObjects = [jParse, jparse1];
}
var vparse = JSON.stringify(arrayOfObjects);
var vparse1 = JSON.parse(vparse);
sessionStorage.removeItem('empData');
sessionStorage.setItem("empData", vparse);
}
}
</script>
But when I retrieve the data from sessionStorage after assigning data this is not giving me proper json format can some one help me. This is the format I am getting
"["\"{\\"employees\\":[{\\"firstName\\":\\"John\\",\\"lastName\\":\\"Doe\\"},{\\"firstName\\":\\"Anna\\",\\"lastName\\":\\"Smith\\"},{\\"firstName\\":\\"Peter\\",\\"lastName\\":\\"Jones\\"}]}\"","{\"employees\":[{\"firstName\":\"John1\",\"lastName\":\"Doe1\"},{\"firstName\":\"Anna1\",\"lastName\":\"Smith1\"},{\"firstName\":\"Peter1\",\"lastName\":\"Jones1\"}]}"]"
When I watch it in console. Also I am using restful service where my service holds a datatable as a parameter how can I pass this json object to that method as DataTable
This is actually a very wide discussed issue:
This is what is proposed by microsof in this article
If this function causes a JavaScript parser error (such as "SCRIPT1014: Invalid character"), the input text does not comply with JSON syntax. To correct the error, do one of the following:
Modify the text argument to comply with JSON syntax. For more information, see the BNF syntax notation of JSON objects.
For example, if the response is in JSONP format instead of pure JSON, try this code on the response object:
var fixedResponse = response.responseText.replace(/\\'/g, "'");
var jsonObj = JSON.parse(fixedResponse);

Categories

Resources