convert json encoded array to javascript array - javascript

i was trying to get the location of the particular device .i am getting the location but can't merge with javascript .
My AJAX is returning JSOn Encoded Array Like
[{"title":"Thudi","lat":"11.0812178","lng":"76.94155735"}]
in Java script variable i have to assign this value like -
var markers = [{"title":"NGGO ","lat":"11.0888676","lng":"76.94175196"}];
i tried many methods to convert json array to js variable, array but i am not getting the exact answer

Can you describe you question more clear?
I guess your question is convert returning JSON stirng to JS Object.
JSON.parse(/*returnining json string*/)

Related

How do I use JS regex to capture a specific JSON value after its key? [duplicate]

This question already has answers here:
Parse JSON in JavaScript? [duplicate]
(16 answers)
Closed 5 years ago.
I have JSON data in the following format:
{"User":"aa2","Owner":"aa2_role","Status":"locked","Port":"5432","Description":"Transferred from CFS01 on Jun29","Project":"aa2","Server":"localhost"}
I can count on the key called "Project": to always be the same.
What I need is to pull the Value of the "Project": key which in this case is "aa2" using regex in JavaScript.
I have been trying different variations of /^("Project":)$/g but it is not working.
My last attempt I tried /[^"Project":$]/g but it gives me everything in the JSON Object but "Project":
Does anyone know how I can capture the value of a specific Project key?
EDIT: Just for clarification I agree with the use of the Parsing mechanism. My problem is that I am debugging/working with a previous code base that is using a separate function to pass the parsed JSON as a string into the function where now I need to pull the data needed from the string. After having spent this amount of time trying to come up with a work around I am about to scrap the function in order to use Parse... that's why I'm trying to use regex but the more I think about it, the more I realize that it's just bad code... but still, now I am just curious.
No need to use Regular expression to extract value from object string. Just Use JSON.parse(). This will convert string to Object. After parsing you can use key to access the value.
var obj = JSON.parse('{"User":"aa2","Owner":"aa2_role","Status":"locked","Port":"5432","Description":"Transferred from CFS01 on Jun29","Project":"aa2","Server":"localhost"}');
console.log(obj.Project);
Parse the JSON and then get the value.
Working example : https://jsfiddle.net/vineeshmp/2c8z7r6u/
var json =' {"User":"aa2","Owner":"aa2_role","Status":"locked","Port":"5432","Description":"Transferred from CFS01 on Jun29","Project":"aa2","Server":"localhost"}';
json = JSON.parse(json);
alert(json.Project);

Accessing an array of objects stored in a json file

I am trying to access an array of objects, with javascript, that is stored in a json file on my site. I could just include the array of objects in my js, but I'm trying to learn how to use json files.
I would like to store the array as a variable in my js file. What is the best way to go about this?
You just need to pass the String to:
JSON.parse("{my:'object'}")
To read the file from the server, just use the ajax api.
$.get( "my-endpoint/test.json", function( data ) {
var jsObject = JSON.parse(data)
});
I guess Jquery might already have parsed the data and you do not even need to call JSON.parse() - try it out :)

Converting JS object to json string using JSON.stringify

I have four textboxes which contain json string which I create by calling json.stringify on various js objects..
eg. '["users.name","users.username"]' (This is the value of one textbox)
What I want to do is create a single json string from these four json strings and send them to the backend using POST..
So I create a object and add them like this
tmp = {}
tmp["columns"] = $("#sc").val();
/*adding more data....*/
$.ajax("/api/backend", {
data: JSON.stringify(tmp),
/* more ajax code...*/
});
The data that gets sent is of the following format..
{"columns":"[\"users.name\",\"users.username\"]"}
This is not a string but a json object...
Now when I do the following..
tmp1= JSON.stringify(tmp)
and Post using..
$.ajax("/api/backend", {
data: JSON.stringify(tmp1),
/*more code below..*/
The data that gets sent is of the following format and is string..
"{\"columns\":\"[\\\"users.name\\\",\\\"users.username\\\"]\"}"
This string has a lot of '\' characters which needs to be taken into account in the backend.
Is this the right way of handling my problem or am I doing something wrong?
Thanks
It depends on what you are trying to achieve.
If you want to send to the server a JSON that combines all JSON in your inputs, you'd better parse the JSON in your inputs, prior to adding them to you tmp object. That way, you get an object containing objects, rather than an object containing JSON strings.
Retrieving JSON from inputs would be like this:
tmp["columns"] = JSON.parse($("#sc").val());
See that you are storing objects within your tmp object, rather than JSON strings. Then, you can just send that object as JSON to your server.
Thus, your server would receive this:
"{\"columns\":\"[\"users.name\",\"users.username\"]\"}"
Which, I believe, looks much better. I hope that helps.

Get Data from Text File to Multidimensional Array Javascript

I have a little bit of an issue with a JavaScript function that needs to read data from a TextFile (something JS is already limited with) and then process tha TextFile data into a MultiDimensional Array (another thing that JS doesn't nativelly suport).
With that in mind, I have a text file in this format:
1, Name, Data, Serial
2, Name, Data, Serial
3, Name, Data, Serial
And so on.
So, the objective is to get that same data and put it, like that, into an array.
I suppose that, from what I've been reading, I need an Array of an Array, segmenting the first one by lines [/n] and the second one by commas [,]. However, given the "by-default" limitations, I'm very confused at this point. I do suppose I need jQuery, however.
I tried this:
var fs = require('fs');
var array = fs.readFileSync('file.txt').toString().split("\n");
for(i in array) {
var array = fs.readFileSync('file.txt').toString().split(",");
for(f in array) {
}
}
With little success, because then I don't really know how to store it, the objective being a Multidimensional Array that Replicates the Format of the text file, so latter it could be used to search by index or instance following an user input to get results.
I really appreciate any help.
At first glance it seems like you are trying to read in a CSV file. If that is indeed the case I recommend node-csv:
http://www.adaltas.com/projects/node-csv/
https://github.com/wdavidw/node-csv
This helped me reading file to JavaScript, however this example converts retrieved data to JSON. Just looking at the format of your text file, I would assume a JSON string or Javascript object would work with your data.
Example convert to JSON
With JSON and JS objects, instead of referencing a array indexes eg. array[i][x]. you would replace [x] with .propertyName
data = {
"id": 1,
"name": "Fred"
};
//access data like this
data[i].name //will return "Fred" as i =0
to create JS object, just initialize array properties without the ""(quotation marks). accessing JS and JSON properties are done in the same way, main advantage over a multidimensional array is that you can reference an actual property name, as opposed to indexes.

Passing JavaScript array to input in PHP

I'm trying to pass an array from JavaScript to a PHP input. I want to pass my array as an array inside my input, not a string.
My array is this:
["0_1","0_2"]
And this is how I pass my array to my input:
$('#movefile_id').val(JSON.stringify(allfiledata));
Can I pass the array to the input file without making it a string?
read this:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
you can convert your array to JSON
var arrayJavascript = JSON.stringify(["0_1","0_2"]);
and with PHP, read this:
http://php.net/manual/es/function.json-decode.php
$arrayPHP = json_decode($_POST["arrayJavascript"]);
Here is the step by step process given below
1- Covert the Javascript Array to JSON
2- Post that JSON string to PHP using jquery post or jquery get
This is possible through only using Ajax. Because javscript is a Client side language and PHP is a server side language.We can only connect both using Ajax.

Categories

Resources