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

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))

Related

How to make JavaScript object from the given json string

I have a large json data that I have to parse and get object out of the following Json string. I added just top part of that large json data. I tried to parse it by
let obj = JSON.parse(this.state.data);
it doesn't work, it breaks with this msg "SyntaxError: Unexpected token L in JSON at position 0".
If I get the console.log by console.log(JSON.stringify(this.state.data, null, 2)); and try to validate output by online JSON validator, it says it is valid JSON data. Could you please tell me how can I parse it?
{
"content": [
{
"_id": 1,
"name": "Warehouse A",
"location": {
"lat": 47.13111,
"long": -61.54801
},
"cars": {
"location": "West wing",
"vehicles": [
{
"model": "GX",
"price": 27395.26,
"licensed": false,
"_id": 15,
"make": "Lexus",
"year_model": 2005,
"date_added": "2017-11-12T00:00:00.000+00:00"
},
{
"model": "Q",
"price": 6103.4,
"licensed": false,
"_id": 9,
"make": "Infiniti",
"year_model": 1995,
"date_added": "2017-11-13T00:00:00.000+00:00"
},
.........xxxxxx continue
Your variable this.state.data is not a JSON. It's a Javascript Object, just like JSON, So, Why not just use let obj = this.state.data;

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

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>

Using underscore.js to find values in deeply nested JSON

I'm pretty new to Javascript, and I just learned about underscore.js. I have a deeply nested JSON object, and I need to use underscore to find key/value pairs, which I will then use to populate various HTML tables. If the structure was more shallow, using something like _.pluck would be easy, but I just don't know how to traverse past the first couple of nesting levels (i.e. surveyGDB, table, tablenames). The JSON object comes from an XML that is comprised of multiple nesting structures (mashed up from different database tables).
var JSONData =
"surveyGDB": {
"filename": "..\\Topo\\SurveyGeoDatabase.gdb",
"table": {
"tablename": [
{
"#text": "SurveyInfo\n ",
"record": {
"OBJECTID": "1",
"SiteID": "CBW05583-345970",
"Watershed": "John Day",
"VisitType": "Initial visit",
"SurveyInstrument": "Total Station",
"ImportDate": "2015-07-22T09:08:42",
"StreamName": "Duncan Creek",
"InstrumentModel": "TopCon Magnet v2.5.1",
"FieldSeason": "2015"
}
},
{
"#text": "QaQcPoints\n ",
"record": [
{
"OBJECTID": "1",
"TIMESTAMP": "2015-07-22T09:18:43",
"Code": "tp",
"Count": "357"
},
{
"OBJECTID": "2",
"TIMESTAMP": "2015-07-22T09:18:43",
"Code": "tb",
"Count": "92"
},
{
"OBJECTID": "3",
"TIMESTAMP": "2015-07-22T09:18:43",
"Code": "to",
"Count": "8"
},
{
"OBJECTID": "4",
"TIMESTAMP": "2015-07-22T09:18:43",
"Code": "bl",
"Count": "279"
},
{
"OBJECTID": "5",
"TIMESTAMP": "2015-07-22T09:18:43",
"Code": "bf",
"Count": "18"
}
]
},
{
"#text": "QaQcPolygons\n ",
"record": [
{
"OBJECTID": "1",
"TIMESTAMP": "2015-07-22T09:43:08",
"SurveyExtentCount": "",
"WaterExtentCount": "",
"ChannelUnitsCount": "",
"ChannelUnitsUnique": ""
},
{
"OBJECTID": "2",
"TIMESTAMP": "2015-07-22T13:35:15",
"SurveyExtentCount": "1",
"WaterExtentCount": "1",
"ChannelUnitsCount": "21",
"ChannelUnitsUnique": "21"
}
]
}
]
}
}
}
For instance, I wanted all of the values for 'Code' in the 'QaQCPoints' table, so I tried:
var codes = _.flatten(_.pluck(JSONData.surveyGDB.table.tablename[1].record[0], "Code" ));
console.log(codes);
In the console, this returns an array with a length of 5, but with blank values.
What am I doing wrong?
I'd also rather search for the 'Code' values in the table based on something like the '#text' key value, instead of just using it's position in the object.
If I understood you correctly, you want to always search the record array within JSONData.surveyGDB.table.tablename array for some queries. This means you need to find the record based on some parameter and return something from the found record.
Do note that the record property is sometimes an array and sometimes an object (for table SurveyInfo) in your example so I'll assume you need to take this into account.
You can make a small function to extract data and handle both objects and arrays:
function extract(record, prop) {
if (Array.isArray(record)) {
return _.pluck(record, prop);
} else {
return record[prop];
}
}
Usage example:
I wanted all of the values for 'Code' in the 'QaQCPoints' table.
I'd also rather search for the 'Code' values in the table based on something like the '#text' key value, instead of just using it's position in the object.
To achieve this you first find a record using _.find, and then extract Code values from it using the method above:
var table = JSONData.surveyGDB.table.tablename;
// find an item that has `#text` property equal to `QaQcPoints`
var item = _.find(table, function(r) {
return r['#text'] === 'QaQcPoints';
});
// extract codes from the found item's record property
var code = extract(item.record, 'Code');
// output ["tp", "tb", "to", "bl", "bf"]
Running sample:
var JSONData = {
"surveyGDB": {
"filename": "..\\Topo\\SurveyGeoDatabase.gdb",
"table": {
"tablename": [{
"#text": "SurveyInfo",
"record": {
"OBJECTID": "1",
"SiteID": "CBW05583-345970",
"Watershed": "John Day",
"VisitType": "Initial visit",
"SurveyInstrument": "Total Station",
"ImportDate": "2015-07-22T09:08:42",
"StreamName": "Duncan Creek",
"InstrumentModel": "TopCon Magnet v2.5.1",
"FieldSeason": "2015"
}
}, {
"#text": "QaQcPoints",
"record": [{
"OBJECTID": "1",
"TIMESTAMP": "2015-07-22T09:18:43",
"Code": "tp",
"Count": "357"
}, {
"OBJECTID": "2",
"TIMESTAMP": "2015-07-22T09:18:43",
"Code": "tb",
"Count": "92"
}, {
"OBJECTID": "3",
"TIMESTAMP": "2015-07-22T09:18:43",
"Code": "to",
"Count": "8"
}, {
"OBJECTID": "4",
"TIMESTAMP": "2015-07-22T09:18:43",
"Code": "bl",
"Count": "279"
}, {
"OBJECTID": "5",
"TIMESTAMP": "2015-07-22T09:18:43",
"Code": "bf",
"Count": "18"
}]
}, {
"#text": "QaQcPolygons",
"record": [{
"OBJECTID": "1",
"TIMESTAMP": "2015-07-22T09:43:08",
"SurveyExtentCount": "",
"WaterExtentCount": "",
"ChannelUnitsCount": "",
"ChannelUnitsUnique": ""
}, {
"OBJECTID": "2",
"TIMESTAMP": "2015-07-22T13:35:15",
"SurveyExtentCount": "1",
"WaterExtentCount": "1",
"ChannelUnitsCount": "21",
"ChannelUnitsUnique": "21"
}]
}]
}
}
}
function extract(record, prop) {
if (Array.isArray(record)) {
return _.pluck(record, prop);
} else {
return record[prop];
}
}
var table = JSONData.surveyGDB.table.tablename;
var item = _.find(table, function(r) {
return r['#text'] === 'QaQcPoints';
});
console.dir(item);
var code = extract(item.record, 'Code');
console.log(code);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
You have a two stage problem. Stage one is figuring out which table is QaQcPoints. If that's always JSONData.surveyGDB.table.tablename[1], you're good.
The next stage is getting your data out. You can use native array manipulation most of the time (unless you're on really old browsers). So:
var table = JSONData.surveyGDB.table.tablename[1].record;
var codeArray = table.map(function(val) { return val.Code; });
Will do the trick.

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

Categories

Resources