Nested json data in js -get the values from nested array - javascript

Got the output result in json nested array.
Help to access the USER-id of this json format .
var result = {
"USER": {
"id": "11456",
"email": "g#gmail.com",
"name": "g"
},
"status": "true",
"group-title": "title",
"group-name": "2-Group"
}

I thin your json structue is wrong. Below is the corrected structure
{
"status": "true",
"USER": {
"id": "11456",
"name": "g",
"email": "g#‌​gmail.com"
},
"group-name": "2-Group",
"group-title": "title"
}
The json usages in JS
var result={ "status": "true", "USER": { "id": "11456", "name": "g", "email": "g#‌​gmail.com" }, "group-name": "2-Group", "group-title": "title"};
resultJson=jQuery.parseJSON(result);
var userId=resultJson.USER.id; // here you will get the user id
Please try this way. This may help you. Don't forget to add jQuery in your script

json values are not seperated by
;
the correct formate for your json is
var result = {"status":"true","USER":{"id":"11456","name":"g","email":"g#gmail.com"},
"group-name":"2-Group","group-title":"title"}
for this formate u can assess the user id by
result.USER.id;

From your code, you can directly access Id as below:
<script>
var result = {
"USER": {
"id": "11456",
"email": "g#gmail.com",
"name": "g"
},
"status": "true",
"group-title": "title",
"group-name": "2-Group"
};
alert(result.USER.id);
</script>

Related

trouble while parsing json

I am trying to react displayName in req
when I write
console.log(req.session.passport.user._raw)
the output is:
{
"kind": "plus#person",
"etag": "\"ucaTEV-ZanNH5M3SCxYRM0QRw2Y/XiR7kPThRbzcIw-YLiARoF22TMY\"",
"emails": [
{
"value": "rajanlagah#gmail.com",
"type": "account"
}
],
"objectType": "person",
"id": "100428644453494579140",
"displayName": "Rajan Lagah",
"name": {
"familyName": "Lagah",
"givenName": "Rajan"
},
"url": "https://plus.google.com/100428644453494579140",
"image": {
"url": "https://lh3.googleusercontent.com/-XdUIqdMkCWA/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg?sz=50",
"isDefault": true
},
"isPlusUser": true,
"language": "en",
"circledByCount": 0,
"verified": false
}
Now the from this object I am trying to get kind (say)
console.log(req.session.passport.user._raw.kind)
then the output is undefined
Can any one tell my mistake?
Is req.session.passport.user._raw a string? You may need to parse it first, eg:
var data = JSON.parse(req.session.passport.user._raw);
console.log(data.kind);

Creating Complex JSON Object using JavaScript Code

I am bit new to JSON world. And I have to use JavaScript to create following type of JSON structure. Not sure how to achieve this. Tried with following code, but unable to add second element("12101") as well as people to JSON Structure is where I am struggling.
var chat = {};
chat = {"101":{}};
chat["101"].people= {};
chat["101"].people = {"L0b12leL-Ar9GYKoAAAC":{}};
chat["101"].people.L0b12leL-Ar9GYKoAAAC = {"name":"vikram#qech.com"};
chat["101"].room= {};
JSON structure to achieve
{
"101": {
"people": {
"L0b12leL-Ar9GYKoAAAC": {
"name": "vikram#qtech.com",
"inroom": "f787f316-6424-491b-b779-cfc396f0f8a1",
"owns": "f787f316-6424-491b-b779-cfc396f0f8a1",
"countrycode": "in",
"device": "desktop",
"roomname": "R1"
},
"qKCglYWI1hRhZUZCAAAD": {
"name": "Ishim",
"inroom": "2e52905d-951c-4990-b9b7-2f3fc0602922",
"owns": "2e52905d-951c-4990-b9b7-2f3fc0602922",
"roomname": "Ra"
}
},
"room": {
"f787f316-6424-491b-b779-cfc396f0f8a1": {
"name": "R1",
"id": "f787f316-6424-491b-b779-cfc396f0f8a1",
"owner": "L0b12leL-Ar9GYKoAAAC",
"people": [
"L0b12leL-Ar9GYKoAAAC"
],
"status": "available"
},
"2e52905d-951c-4990-b9b7-2f3fc0602922": {
"name": "Ra",
"id": "2e52905d-951c-4990-b9b7-2f3fc0602922",
"owner": "qKCglYWI1hRhZUZCAAAD",
"people": [
"qKCglYWI1hRhZUZCAAAD"
],
"status": "available"
}
}
},
"12101": {
"people": {
"K-Ar9GYKoAAAC": {
"name": "Rahul.com",
"inroom": "f787f316-6424-491b-b779-cfc396f0f8a1",
"owns": "f787f316-6424-491b-b779-cfc396f0f8a1",
"countrycode": "in",
"device": "desktop",
"roomname": "R1"
},
"I1hRhZUZCAAAD": {
"name": "Vipul",
"inroom": "2e52905d-951c-4990-b9b7-2f3fc0602922",
"owns": "2e52905d-951c-4990-b9b7-2f3fc0602922",
"roomname": "Ra"
}
},
"room": {
"b779-cfc396f0f8a1": {
"name": "Rahul-R1",
"id": "f787f316-6424-491b-b779-cfc396f0f8a1",
"owner": "L0b12leL-Ar9GYKoAAAC",
"people": [
"L0b12leL-Ar9GYKoAAAC"
],
"status": "available"
},
"b9b7-2f3fc0602922": {
"name": "Vipul-Room1",
"id": "2e52905d-951c-4990-b9b7-2f3fc0602922",
"owner": "qKCglYWI1hRhZUZCAAAD",
"people": [
"qKCglYWI1hRhZUZCAAAD"
],
"status": "available"
}
}
}
}
This is invalid because the property name contains dashes.
chat["101"].people.L0b12leL-Ar9GYKoAAAC = {"name":"vikram#qech.com"};
To access it correctly, put it in quotes
chat["101"].people["L0b12leL-Ar9GYKoAAAC"] = {"name":"vikram#qech.com"};
Use bracket notation as a property accessor like this:
chat["12101"].people = {};
chat["101"].people["L0b12leL-Ar9GYKoAAAC"] = {"name":"vikram#qech.com"};
With it, it’s just a routine piece of work. It probably didn’t work right away since dot notation property access requires a valid identifier name. With bracket notation, you can use any string like "L0b12leL-Ar9GYKoAAAC".
Also note that in JSON, anything works as a property name too, as long as it is put in quotes. {"L0b12leL-Ar9GYKoAC":true} is as valid as {"💖":true}.

Working With Dynamic Multidimensional key-value pairs in JSON

Having a thorny problem and only see similar but also simpler solutions on SO.
Is is possible to generate a dynamic key AND dynamic values using JS/JSON?
For instance, let's say I have JSON like this:
{
"email": "user#someco.com",
"firstname": "Bob",
"lastname": "Smith",
"company": "ACME",
"custom": {
"services": [
{
"name": "svc1",
"desc": "abcdefg",
"selected": "true",
"status": "None"
},
{
"name": "svc2",
"desc": "abcdefg",
"selected": "true",
"status": "None"
},
{
"name": "svc3",
"desc": "abcdefg",
"selected": "false",
"status": "None"
},
{
"name": "svc4",
"desc": "abcdefg",
"selected": "false",
"status": "None"
}
],
"fields": [
{
"name": "Products",
"desc": "abcdef",
"type": "multi",
"values": [
{
"name": "Product1",
"desc": "abcdef"
},
{
"name": "Product2",
"desc": "abcdef"
}
],
"services": [
"svc1",
"svc2",
"svc3"
]
},
{
"name": "Wines",
"desc": "abcdef",
"type": "multi",
"values": [
{
"name": "Wine 1",
"desc": "abcdef"
}
],
"services": [
"svc4"
]
},
{
"name": "Fruits",
"desc": "abcdef",
"type": "multi",
"values": [
{
"name": "Fruit 1",
"desc": "abcdef"
},
{
"name": "Fruit 2",
"desc": "abcdef"
}
],
"services": [
"svc4"
]
}
]
}
};
I need to go into the fields and for each field (products, wines, fruits) see if a given service is contained within so that I can go back and generate a product or wine or fruit for each service that requires it. But I don't want to repeat the services names more than once. The resulting JSON should look something like this:
{"svc1":["Products"], "svc2":["Products"], "svc3":["Products"], "svc4":["Fruits", "Wines"]}
The hope would be that to generate a dynamic list in Angular I can just turn and loop back through this JSON, pulling out the values for each product, fruit, wine, whatever.
I've been trying a lot of nested for loops and the like but whenever I get more than one layer down the dynamism seems to stop. I'm guessing that for this to work I need to move between JS Objects and JSON?
Right now I'm trying something like this, which isn't quite working, stringify or no. And maybe I'm flip-flopping too much between JSON and JS Objects:
var outObj = [];
var fieldItems;
$.each(jsonObj.custom.fields, function(key, item) {
fieldItems = item;
fieldItems.name = item.name;
$.each(fieldItems.services, function(key, item) {
var serviceName = item;
//check to see if the serviceName already exists
if (outObj.indexOf(serviceName) > -1) {
outObj.serviceName.push(fieldItems.name);
} else {
outObj.push(serviceName);
}
});
});
JSON.stringify(outObj);
console.log("outObj " + outObj);
I get "can't read property 'push' of undefined" errors and the like. Seems this should be possible from a single nested loop, but maybe I need to just do two passes? Any other suggestions?
To me it sounds like overcomplicated solution. You can use basic array methods of javascript to filter out required structure. I am not sure what profiling_value in the presented snippet, so I started from the object structure in OP
var desiredResult = jsonObj.custom.services.reduce(function(result, service){
result[service.name] = jsonObj.custom.fields.filter(function(field){
return field.services.indexOf(service.name) >= 0;
}).map(function(field){ return field.name; });
return result;
}, {});
This gives the expected result for mentioned object.
reduce is required to iterate over all services and accumulate result in one object. Then for each service fields are iterated to filter out only those that contain link to this service. And finally list of filtered fields is transformed (map) into list of strings - their names - and inserted into accumulator

How to manipulate this JSON using Javascript

I am getting this response from an API:
{
"statuses": {
"status": [
{
"name": "Member",
"id": "1"
},
{
"name": "Attender",
"id": "3"
},
{
"name": "Child",
"id": "4"
}
]
}
}
But I need to somehow flatten the response to be this:
{
"name": "Member",
"id": "1"
},
{
"name": "Attender",
"id": "3"
},
{
"name": "Child",
"id": "4"
}
How can I do that using Javascript?
var response = {
"statuses": {
"status": [
{
"name": "Member",
"id": "1"
},
{
"name": "Attender",
"id": "3"
},
{
"name": "Child",
"id": "4"
}
]
}
}
var statusObj = response.statuses.status;
$('#result').text('First name is: ' + statusObj[0].name)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label id="result"/>
You can do JSON.parse(str) and then you you just take the data from status[x]
If you really want to keep it as a string you can do
var content = str.match(/\[(.*?)\]/);
In fact, you just need to retrieve by response.statuses.status from your Javascript object.
But , If you needed to convert json to javascript object,
please use JSON.parse(your json response) method using JSON.js.
Download the JSON.js from https://github.com/douglascrockford/JSON-js

How to get some data from json array length and context [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 8 years ago.
i have some data like :
{
"_id": ObjectId("528ae48e31bac2f78431d0ca"),
"altitude": "110",
"description": [
{
"id": "2",
"des": "test"
}
],
"id": "1",
"latitude": "24.9528802429251",
"longitude": "121.509316013427",
"name": "H hotel"
}
i want get description length and show it context
please help me!!
You don't provide much information, but here's an overview. I'm assuming you have a JSON string and not an object yet. I shall call him, "Jason Data" ...or rather jsonData.
Something like this for illustrative purposes (only without the new lines since you can't do multi-line strings in JavaScript in this fashion, but you get the idea):
// Jason Data, head full of doubt, road full of promises
var jsonData = '{
"_id": "528ae48e31bac2f78431d0ca",
"altitude": "110",
"description": [
{
"id": "2",
"des": "test"
}
],
"id": "1",
"latitude": "24.9528802429251",
"longitude": "121.509316013427",
"name": "H hotel"
}';
And then treat our outpatient, Jason Data:
// let's get his Mona Lisa
var data = JSON.parse(jsonData);
// since he holds numerous memories, let's first get the count (as you wish)
var numDescriptions = data.description.length;
// as if we were psychiatrists, we will now analyze each of his experiences
for ( var i = 0; i < numDescriptions; i++ ) {
// and write a poem about his life. (even though this goes against doctor-patient privilege, sue me)
console.log(data.description[i].id,data.description[i].des);
}
This is a JSON data you can stringfy and parse that data.
var data = JSON.stringify({
"_id": "ObjectId(528ae48e31bac2f78431d0ca)",
"altitude": "110",
"description": [
{
"id": "2",
"des": "test"
}
],
"id": "1",
"latitude": "24.9528802429251",
"longitude": "121.509316013427",
"name": "H hotel"
})
var parseData = JSON.parse(data)
parseData.description.length
1
parseData.description[0].id
"2"
parseData.description[0].des
"test"
Suggestion: You can get the value of ObjectId(528ae48e31bac2f78431d0ca) outside this format, and pass that as String to _id value
First of all you need to validate your json,
{
"_id": "528ae48e31bac2f78431d0ca",
"altitude": "110",
"description": [
{
"id": "2",
"des": "test"
}
],
"id": "1",
"latitude": "24.9528802429251",
"longitude": "121.509316013427",
"name": "H hotel"
}
This is a valid json. Now you can do the desired like this -
$.getJSON('assets/json/demo.json', function(data) {
$.each(data, function(key, value){
if(key === 'description'){
var description_length = value.length;
}
});
});
And to display its content you can again loop over "description" some what like this -
$.each(value, function(index, val){
alert(index+'-'+val);
});
Your question is not clear, anyway if you are looking to get value corresponding to key "description" then try this yourdata.description to get it's value
I have created these steps at http://jsfiddle.net/twmSk/1/
//storing your data into variable yourdata
var yourdata = {
"_id": ObjectId("528ae48e31bac2f78431d0ca"),
"altitude": "110",
"description": [
{
"id": "2",
"des": "test"
}
],
"id": "1",
"latitude": "24.9528802429251",
"longitude": "121.509316013427",
"name": "H hotel"
}
$('#test').html(JSON.stringify(yourdata.description))

Categories

Resources