JSON parsing and stringify - javascript

I am currently working on a Javascript project where I have to parse tons of data. The project requires that I parse some JSON data and bring specific data into another array. Right now, I am using the JSON.stringify method and I can console.log all of the data that I need. The data looks something like this:
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
-85.3865810000125,
33.90171899971196
],
[
-85.38659500025622,
33.9017919996593
],
yes, this is not all that data-it is about 1200 pages long! I only pasted in the top segment of it. All I really need is how to get to the coordinates aspect of it and into an array. So what I am currently doing is this:
var work = JSON.stringify(response, null, 4)
console.log(work);
Which gives me the above response. However, I am not that familiar with JSON.stringify so if I do:
console.log(work.type);
Attempting to see what the value is for type, I get a response of undefined. Now if I try doing this:
var work = JSON.parse(response)
console.log(work);
I get a response of: VM296:1 Uncaught SyntaxError: Unexpected token o in JSON at position 1
Thus, I cannot get the data parsed which I want to get to which will be the coordinates data. Any help with using stringify would great help me. I have read a lot about how it turns the data into a string but have not really seen a lot about how to parse it. Do I have to use parse? Thank you for your help!

You dont' have to use stringify or parse for this. The response object you are receiving is already a javascript object so you can reference its properties normally
response.type; // => "FeatureCollection"
If you try and stringify the response it will lose its type property, for instance:
typeof "some string".someProperty; // => undefined

Related

JavaScript: read and write json file

I have generated json file from my consumer pact in javaScript. When it's generating json file it doesn't contain what I expect. So, now I want to add block to my json file which I don't know how to do? Can someone here help me with that? so, basically I want to read json then create block and then write into json and save data
"path": {
"dataType": "String",
"expression": "data/xml/${id}",
"key": "request"
}
Thanks,
As #Barmar pointed out you can simply parse your JSON text and modify it.
let yourJsonText = "{...}"; // read in your json however you want
let yourJson = JSON.parse(yourJsonText);
// then modify your object
yourJson.path.newAttr = "something you like";
// parse it back to a JSON string
let yourUpdatedJsonText = JSON.stringify(yourJson);

AWS Lambda: How do I get property inside event.body, it keep return undefined

I was trying to get event.body.data, but it keep return me undefined, i tried JSON.parse(event), JSON.parse(event.body), JSON.parse(event.body.data), JSON.stringify, almost tried out things that i can do with JSON and non of them seems to work. When i tried JSON.parse(event), will give syntax error. So i suspect it already in JSON object format and when i console.log it, it didn't have the " " quote. If it is already in JSON format, why can't I access the property in it. I also tried wrap it inside if(event.body.data) and it doesn't work as well. Anyone know how to get property inside event.body?
Based on your screenshot it looks like the body data is a JSON string. That means you have to parse it first before you can use it. Something like this:
exports.handler = function(event, context, callback) {
const body = JSON.parse(event.body)
console.log('data: ', body.data)
}
Then apply the suggestions from #Marcin and fix your JSON data because it's missing quotes.
Your even.body is invalid json string, which explain why JSON.parse fails. Thus, you should check who/what is making the request and modify the code of the client side to invoke your API with a valid json string.
It should be:
'{"action": "message, "data": "black clolor"}'
not
"{action: 'message, data: 'black clolor'}"
Thanks #Marcin for the feedback, it was indeed caused by invalid json string sent from frontend.
Changing it to the code below solved the issue.
{"action": "message", "data": "black clolor"}

how to solve problem getting json object element

I have a json object that i want to use.
{
"type": "PROVIDER_PAYLOAD",
"message": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVkOTQ3OTg4N2RlMGRkMDc4ZjEzM2FmNyIsImVtYWlsIjoiYWxzb25nZHVuc3RhbjJAZ21haWwuY29tIiwicm9sZSI6IkNVU1RPTUVSIiwiaWF0IjoxNTcwMDI3MDA4fQ.FcpoBPmhTSX535bNgE2ezCCWsNFPjEhc87hM4y6WadM"
}
so when i try to access it using
console.log("Postback: " + payload.type)
but i get an error of
Postback: undefined
i have looked over some resources on the web and most of them do it this way and it works but i am not sure why mine is not giving the value for type
thanks in advance
Subh is right. You have to parse the JSON into an object before accessing type using payload.type syntax.
So, let's say you have the following:
let payload = {
"type": "PROVIDER_PAYLOAD",
"message": "eyJhbGciOiJIUzWadM"
}
You have to convert it into a JS object using JSON.parse:
let payloadObj = JSON.parse(payload);
Now, if you do payloadObj.type, you should be fine.
console.log(payloadObj.type); // PROVIDER_PAYLOAD
It should work fine.
UPDATE: ERROR: SyntaxError: Unexpected token a in JSON at position 0
If you are getting this error, try following to Parse the payload.
let payloadObj = JSON.parse(JSON.stringify(payload))
It should solve the problem for you.

convert mongodb object to javascript object

I pass a config file to another node.js module when starting it. The config file contain the following json:
"resolution": {
"activated": true,
"types": [
{"of": 23}
]
}
When I print the received types array in the called node.js module, it looks like
console.log('types array: '+ this.config.resolution.types)
//output
types array: [object Object]
if I tried to print the text by using JSON.stringify(), I get the following result
[{"of":23}]
My problem start when I try to replace the types array with a list retried from a mongodb database. my code looks like:
"resolution": {
"activated": true,
"types": [
savedTypes
]
}
Now when I print the received types config, it looks like this:
types array: { _id: 5ab9fe8fd1f64303cd98f122, of: 23, __v: 0 }
and the called node module is not working properly with this config. How can I cast this to an object? I tried to use
JSON.parse(savedTypes)
and get the error
SyntaxError: Unexpected token _ in JSON at position 2
If you use mongoose, I think that the correct form is using ToJSON() function.
Otherwise, you can use JSON.parse(JSON.stringify(data)); But I think that de first form is better.
=)
Alternatively you could use .toObject() method from javascript to convert mongoose object into javascript object.
Here is a reference link to dig out more
https://alexanderzeitler.com/articles/mongoose-tojson-toobject-transform-with-subdocuments/

Double parse JSON data (or use another method to split)

Wondering what the best way is to break a large data object coming from AJAX apart. If I send just one portion (says paths) I use JSON.parse(data) What I'd really like to do is split the object apart first into it's individual blocks, then be able to do something like JSON.parse(data['paths']).
Here's a clipped sample of the JSON data
{
"paths": {
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"geometry": {
"type": "MultiLineString",
"coordinates": [
[
[-122.32074805731085, 47.634990818586026],
[-122.32074412999432, 47.63497931696752],
[-122.32107629703529, 47.63465666282262]
]
]
},
"properties": {
"path_name": "Woodland path"
},
"id": 2
}]
},
"beds": {
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"geometry": {
"type": "MultiPolygon",
"coordinates": [
[
[
[-122.32073753862116, 47.6347629704532],
[-122.32071585642394, 47.63470617810399],
[-122.32073753862116, 47.6347629704532]
]
]
]
},
"properties": {
"bed_name": "Azalea Triangle"
},
"id": 1
}]
}
}
Here's what I have in javascript
$.ajax
dataType: 'text'
url: 'map.json'
success: (data) ->
Here's the Rails code that generates the call
data = { buildings: #geopaths, lawns: #geobeds }
respond_to do |format|
format.json { render json: data }
format.html
end
UPDATE:
I had sort of avoided explaining what I was wanting to do because I thought it would confuse the issue. In a nut shell - I am collecting data from a database, and sending it to Javascript to be displayed as layers on a map. Each layer has a name (paths, beds, etc), and gets encoded as GeoJSON in Rails before being sent to Javascript with an AJAX command. If I only send one layer I have no trouble parsing the data and getting it onto the map. A typical line of code would look like pathMarkers = L.geoJSON(JSON.parse(data)).
I now need to pass multiple layers to the map. My understanding is AJAX can only handle one object so I combine both paths and beds into one object. When I get to the Javascript side I don't know what to do. In other words I need to get only that portion of the object that has path data for the pathMarkers, and only that portion of the object that has bed data for the bedMarkers.
Graphically this is what I'm trying to do:
paths = a bunch of GeoJSON data
beds = a bunch of GeoJSON data
Use AJAX to send paths and beds to javascript
build pathMarkers with JSON.parse for the paths data
build bedsMarkers with JSON.parse for the beds data
I could build a sample and post it to bitbucket if it would help.
Assuming that I understood correctly and your concern is bringing in distinct data layers into a geo library like Leaflet.js, a single AJAX request is fine unless the JSON payload is so large that it crashes the browser.
As you don't provide much of your code, the following is a general example of how you would do it.
First you create the map object. Obviously :)
const map = L.map(id).setView([1.2345, -1.2345], 10);
Start the AJAX request to fetch the geoJSON file.
$.ajax({
dataType: "json",
url: '/json/lives/here.json',
data: {} /* any props you'd like to pass as query string to your server */,
success: success
});
And the crux of the issue: "How do I access each feature collection?"
The sucess or done callback is where you can be sure you received the data, and can add it to the map.
jQuery's AJAX method, when called with dataType: 'json', automatically runs JSON.parse() for you (and a couple of other things). Once the JSON is parsed, it can be accessed as any other object in JS.
At this point the success callback receives the JSON-turned-into-object, which you can access with traditional JS methods. Like so:
function success (data) {
// data is the parsed JSON. It is now just a JS object.
// Below: for every "key" in the data object, pass its data to L.geoJSON() and add it to the map.
for (var geojsonFeatureCollection in data) {
if (data.hasOwnProperty(geojsonFeatureCollection)) {
L.geoJSON(geojsonFeatureCollection, {/* options */}).addTo(map);
}
}
}
To answer your point about AJAX and a single object: AJAX is a just like any other browser request.
Yes you do send one request at a time. And likewise you receive one response from the server. But what is contained in the response can be absolutely any data. So what you are doing server side is totally OK!
In your case the data consists of a JSON text file, which is later parsed and turned into a JS object for you to actually do something with. The object contains a bunch of "keys" (beds, paths) and all you need to do is iterate over each of those keys and pass each one to Leaflet's geoJSON method for rendering.
I've run into this problem before with incredibly large payloads on mobile devices (iOS with Phonegap, to be precise). You may want to look into a library named OboeJS, at http://www.juancaicedo.com/oboe.js-website/.
Essentially, that library streams the JSON request so that you can process it in chunks. You should be able to use this to suit your needs.

Categories