How to make JavaScript object from the given json string - javascript

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;

Related

JSON weird format access data

This is a JSON snip that is created in WooCommerce by a plugin that adds some metadata. I cannot change the formatting of this JSON because it is generated by a plugin. The problem is that the keys and the values are added in a weird way. I am iterating through the line_items and statically referencing this data which I don't want to do, I would like to know if there is a smart way to reference for example:
"key": "_cpo_product_id",
"value": "3572",
if this was formatted correctly it would be: "_cpo_product_id": "3572" and not have "value" as a key, and it would be accessed by: foo.line_items[i]._cpo_product_id
but with this configuration I am a bit lost, I am sure there is an easy way to find the value for a specific key. I am doing this on Google app scripts, but a solution in JavaScript should suffice.
JSON snip:
"line_items": [
{
"id": 749,
"name": "Dune",
"product_id": 3572,
"variation_id": 0,
"quantity": 1,
"tax_class": "",
"subtotal": "149.54",
"subtotal_tax": "31.40",
"total": "149.54",
"total_tax": "31.40",
"taxes": [
{
"id": 24,
"total": "31.403148",
"subtotal": "31.403148"
}
],
"meta_data": [
{
"id": 11919,
"key": "_cpo_product_id",
"value": "3572",
"display_key": "_cpo_product_id",
"display_value": "3572"
},
{
"id": 11920,
"key": "_add-to-cart",
"value": "3572",
"display_key": "_add-to-cart",
"display_value": "3572"
},

Javascript JSON.parse() not working on a valid JSON string

I have looked at all similar questions to mine but cannot find any obvious errors in my code or my JSON string.
The script sends a request to a web service, which returns a JSON formatted string. Somehow, html related to debugging is getting tacked onto the end of the JSON string, so I remove it with the string.slice method, to return only the content between the opening and closing square brackets. When I output the slice, everything is there. When I check the resultant slice for proper JSON formatting in jsonlint, it passes. But when I try to parse the string and create an alert of the parsed data, I get an error: Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse ) at XMLHttpRequest.request.onload
Here is the JSON string after slicing, taken directly from the jsonlint output:
[{
"user_id": "23",
"name": "Steven Marsden",
"email": "naturevet1#gmail.com",
"password": "$2y$10$FjDZAugd2Mj9tw.z8U1mWexLF0vkD7jnB5xusGyClDUXZwQC6u9iy",
"address": "2639 Valley Rdg Rd, Blairmore, AB T0K 0E0, Canada",
"lat": "49.617134",
"lng": "-114.388893",
"created_at": "2021-06-06 18:00:20",
"updated_at": "2021-06-06 18:00:20",
"services": [{
"u_s_id": "2",
"user_id": "23",
"mode": "seek",
"service": "pet sitting",
"details": "I have a dragon",
"img_file": null
}, {
"u_s_id": "3",
"user_id": "23",
"mode": "offer",
"service": "pet sitting",
"details": "I love dragons",
"img_file": null
}, {
"u_s_id": "7",
"user_id": "23",
"mode": "offer",
"service": "pet foster home",
"details": "Is it okay if my dragon eats your pet?",
"img_file": null
}],
"color": "red"
}]
Here is the javascript that requests the string and tries to parse it:
var url = 'http://localhost/helpinghands/public/index.php/services/getUsers';//Gets all users, complete with services offered and the appropriate marker color
var request = new XMLHttpRequest();
request.open('GET',url);
request.onload = function(){
if(request.status === 200){
var resp = request.responseText;
var slice = resp.slice(resp.indexOf('['),resp.indexOf(']')+1);//Cleaves any extraneous info from end of string to avoid JSON parse errors
var data = JSON.parse(slice);
//var userLat = Number(data[0].lat);
alert(data);
//var userLong = Number(data.lng);
//const loc = new point(userLat,userLong);//This is the location from the database for that user
//create marker object for loc by passing Marker constructor references to the loc and map objects, which are assigned to position and map variables, respectively
//const marker = new google.maps.Marker({map: map,position: loc, title: data.name});
}
};
Can anyone help me out?
Here is the output from the web service:
[{
"user_id": "23",
"name": "Steven Marsden",
"email": "naturevet1#gmail.com",
"password": "$2y$10$FjDZAugd2Mj9tw.z8U1mWexLF0vkD7jnB5xusGyClDUXZwQC6u9iy",
"address": "2639 Valley Rdg Rd, Blairmore, AB T0K 0E0, Canada",
"lat": "49.617134",
"lng": "-114.388893",
"created_at": "2021-06-06 18:00:20",
"updated_at": "2021-06-06 18:00:20",
"services": [{
"u_s_id": "2",
"user_id": "23",
"mode": "seek",
"service": "pet sitting",
"details": "I have a dragon",
"img_file": null
}, {
"u_s_id": "3",
"user_id": "23",
"mode": "offer",
"service": "pet sitting",
"details": "I love dragons",
"img_file": null
}, {
"u_s_id": "7",
"user_id": "23",
"mode": "offer",
"service": "pet foster home",
"details": "Is it okay if my dragon eats your pet?",
"img_file": null
}],
"color": "red"
}]
var slice = resp.slice(resp.indexOf('['),resp.indexOf(']')+1)
This function applied to your example JSON will cut off everything after the first ], which is the array nested under services, meaning that the first object in the json array will end up unclosed, as well as the json array that wraps the whole response.
You should fix the error in the server that returns HTML inside a JSON payload.
If that's not do-able, then you will need to detect the start of the HTML and cut there, though you are likely to keep experiencing more errors as a result of this faulty server endpoint

angularjs response data does not show in console

i have below code i but data not show in console log please help me i am new in angular.. AND how to show data in HTML
this.$http.get(properties.client+'/123')
.then(response => {
$scope.clientdata= response.data;
console.log($scope.clientdata.address);
});
address array dose not show in console log,i don't know why RESPONSE BELOW
[{ "_id": "123",
"__v": 1,
"history": [],
"address": {
"street_address": "adsf",
"state": "adsf",
"zip_code": "adsf",
"phone_number": "asdf",
"country": "ads",
"city": "asdf",
"site_name": "adsf",
"_id": "123123",
"geolocation": {
"coordinates": [],
"type": "Point"
},
"location": {
"latitude": null,
"longitude": null
},
"id": "5835baaa71a30ca8319b6e36"
},
"current_status": "Assigned",
"time": 0
}]
Your clientdata is an array as per the post, try
console.log($scope.clientdata[0].address);
HTML
{{clientdata[0].address}}
From the structure of your JSON data, clientdata is an array of objects and as of current, there is only one object in the array. So, in order to access the address property of the object, you will have to access it in this way
$scope.clientdata[0].address
and in HTML
{{clientdata[0].address._id}}
and rest of the address object properties in similar fashion.

Access to elements of JSON array of objects [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 7 years ago.
My data on server is in the form of JSON array of objects. If I want to print the first object, how can I access its first object? Format of data is:
[
{
"eventId": "8577",
"datasetId": "34",
"nodeId": "8076",
"typeId": "4",
"type": "TempAndHum",
"status": "Temp : 35, Hum : 83",
"datasetName": "test active set",
"mode": "shared",
"xmlFragment": "Absent",
"gpsLat": "-23.549999",
"gpsLong": "-46.633301",
"contributor": "SanatIITD",
"addedOn": "2015-04-21 08:03:16",
"updatedOn": "2015-04-21 08:03:16"
},
{
"eventId": "8576",
"datasetId": "34",
"nodeId": "8076",
"typeId": "4",
"type": "TempAndHum",
"status": "Temp : 34, Hum : 81",
"datasetName": "test active set",
"mode": "shared",
"xmlFragment": "Absent",
"gpsLat": "-23.549999",
"gpsLong": "-46.633301",
"contributor": "SanatIITD",
"addedOn": "2015-04-21 08:03:11",
"updatedOn": "2015-04-21 08:03:11"
},
{
"eventId": "8575",
"datasetId": "34",
"nodeId": "8076",
"typeId": "4",
"type": "TempAndHum",
"status": "Temp : 33, Hum : 80",
"datasetName": "test active set",
"mode": "shared",
"xmlFragment": "Absent",
"gpsLat": "-23.549999",
"gpsLong": "-46.633301",
"contributor": "SanatIITD",
"addedOn": "2015-04-21 08:03:05",
"updatedOn": "2015-04-21 08:03:05"
},
]
I tried with data[0], but end up with printing "[". I tried with JSON.stringify also and then split with "," but that gives me first element of the object, not the whole first object. I need to print the whole first object which is within the curly braces. Is there any way so that I can access like array and by doing document.getElementById("Id")=myData[0], so that I don't need to print all elements within the curly braces separately. Please suggest me some solution. Thanks in advance.
use var dataArray = JSON.parse(dataString) first,
your data is a string at the moment.
Then use dataArray[0]

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