JSON Array Restful to textarea - javascript

I am working in some code for school and has spend a couple of days looking thru post's but can't find a solution, this is actually my first post and welcome everyone who take the time to help!
I am coding a restful JSON API which I can send the data to the web service, however when I tried to read it and send the data to a textarea, I either get [object, Object] or a 0 (which I think is the index for the array generated from the json).
This is my code for the read function:
function cargarInfo(){
$.get("http://localhost:8080/Lec09/miApi/acciones", function(data, status){
var personas = data.personas;
document.getElementById("info").value = personas;
});
}
When I debug on chrome I can see the Object and the values, I think this is a realy noob question however IDK why I can't figure it out, it is suposed to show the json {nombre:xxxx apellidos:xxxxx} data

You can use JSON.stringify() to stringify your JSON data:
document.getElementById("info").value = JSON.stringify(personas);

Related

Create/Update array data to a JSON file

I am trying to update data properly. I have messed around as much as possible and can't seem to figure it out properly.
I'd appreciate any help in javascript
Data
{"KEWCFN": {"dataId": "KEWCFN","dataName": "12","dataSet": []}}
I want to be able to be able to properly update that JSON data to this.
{"KEWCFN": {"dataId": "KEWCFN","dataName": "12","dataSet": [{set1....},{set2....},{set3....}]}}
Hey im not sure understand your question but if you want to change dataSet in your data Array then you can do this:
Function updateMe(){
Var Data = {"KEWCFN": {"dataId": "KEWCFN","dataName":"12","dataSet": []}} ;
Data.dataSet[0]=‘set1....’;
Data.dataSet[1]=‘set2....’;
Data.dataSet[2]=‘set3....’;
}

How to render json data with # character in its key using handlebars?

This is my json data
var data = {john#gmail.com: true}
In my template i am trying this way to display data but its not working
{{data.[john#gmail.com]}}
I even tried this way
{{data.['john#gmail.com']}}
and also
{{data.john#gmail.com}}
but if i had changed my json data to
var data = {john:true}
and try
{{data.[john]}}
its working and displaying the output as true
Can anyone please point me where i am making mistake ?
It is like this data["john#gmail.com"]. Here is a good Resource to read

JSON cyclic object value when posting data in ChartJS

I'm working with ChartJS to create charts with inputs from the user. It works fine showing the results for more than one dataset, but when I post the data with Javascript using JSON I get this error "cyclic object value". I've been not able to find an answer here, so I'm going to try to explain the issue the best I can.
This is the JS object (myChart.data.datasets) I'm posting, with two datasets from ChartJS:
Then I have a save() function which post that info (working fine for just one dataset) once the chart is done.
function save() {
let data = {
datasets: myChart.data.datasets
};
$.post('/save',
{
savedData: JSON.stringify(data),
color: document.getElementById("color").value,
...
}
)
}
I have no idea what's the cyclic object here, but I know the problem is with the content of myChart.data.datasets being posted. I've used some of the filters from other similar questions, but all them makes some of the data to be lost.
I use the same object to display the chart, which works perfectly with more than one dataset. The problem just happens when posting the data.
Any ideas about what it might be happening? Truly appreciate it, thanks!
This wasn't trivial at all. As many questions & answers regarding cyclic objects in JSON are posted, none of them are very especific about what the solution is. For example, those which use the replacer parameter of JSON.stringify() don't work at all (at least in this case), as the data will be loss.
So, for me the solution was dojox.json.href from the Dojo javascript library. Here's some documentation.
It's not the whole thing, but here's some code in case someone need it. First you serialize the object:
require(["dojox/json/ref"], function(){
let data = {
datasets: dojox.json.ref.toJson(...)
}
$.post('/save',
...
});
And then you deserialize it:
require(["dojox/json/ref"], function(){
data = dojox.json.ref.fromJson(...);
});
You can import the library just like this:
<script src="//ajax.googleapis.com/ajax/libs/dojo/1.13.0/dojo/dojo.js"></script>
This is the only way I've been capable to post the JSON object without loosing data.
Hope it helps!

Converting PHP object to JSON object using only Javascript

I am making a mobile app with Phonegap and using Wordpress as a backend. I am using Advanced Custom Fields with a Google Maps post field which returns a PHP object to the app using JSON API. My Wordpress backend sends a normal JSON object to the app, but inside that object is where a stringified PHP object is returned.
I need to convert the PHP object to a JSON object somehow on the client side(the app which is not in Wordpress). I have looked at other answers that say to use json_encode for this but my problem is that the app is just HTML/Javascript and no PHP. Is there a way to use PHP code in the middle of a Javascript function to do this? Or would it be better to change the backend so that it returns a JSON object instead of a PHP object in the first place? If so, how do I do that?
My experience in PHP is still somewhat limited so any help is appreciated.
edit: To clarify a bit more, I am using Wordpress on a separate domain from my Phonegap app and only using the JSON API plugin on the Wordpress end. I am then using jQuery Ajax calls to retrieve data from the Wordpress backend.
Also the returned PHP object looks like this: a:3:{s:7:\"address\";s:48:\"8915 W 159th St, Orland Hills, IL, United States\";s:3:\"lat\";s:17:\"41.60111599999999\";s:3:\"lng\";s:11:\"-87.8364575\";}
Another way I just thought of as well, would it be possible to just leave it as a PHP object and still read out the values from it somehow? I don't NEED it to be a JSON array, I just need a way to read the individual elements in the array in one way or another.
Here is also a tiny snippet of the JSON returned to clarify what I'm talking about.
"custom_fields": {
"location": [
"a:3:{s:7:\"address\";s:48:\"8915 W 159th St, Orland Hills, IL, United States\";s:3:\"lat\";s:17:\"41.60111599999999\";s:3:\"lng\";s:11:\"-87.8364575\";}"
]
}
That of course isn't the entire JSON object but it gives you an idea of what I'm dealing with.
I know you have a solution that works on the front end, but I still think it'd be better to fix this on the server.
Based on our conversation in the comments, I've had a closer look the code in the WordPress forum. The problem seems to be that the location field is an array of strings, not just a string. maybe_unserialize (and is_serialized, which it uses) don't handle arrays. Here's the updated code, which you should be able to drop into your theme's functions.php. I did a quick test, and it works for me.
class unserialize_php_arrays_before_sending_json {
function __construct() {
add_action( 'json_api_import_wp_post',
array( $this, 'json_api_import_wp_post' ),
10,
2 );
}
function json_api_import_wp_post( $JSON_API_Post, $wp_post ) {
foreach ( $JSON_API_Post->custom_fields as $key => $custom_field ) {
if (is_array($custom_field)) {
$unserialized_array = array();
foreach($custom_field as $field_key => $field_value) {
$unserialized_array[$field_key] = maybe_unserialize( $field_value );
}
$JSON_API_Post->custom_fields->$key = $unserialized_array;
}
else {
$JSON_API_Post->custom_fields->$key = maybe_unserialize( $custom_field );
}
}
}
}
new unserialize_php_arrays_before_sending_json();
If you're using a JSON API to retrieve the data, then why don't you deliver the data in JSON format to your app? Otherwise you seem to remove much of the point of using an API in the first place... You could of course parse that string in JavaScript if you really want to but that's a very ugly and error prone solution.
The JSON API plugin does seem to use JSON:
https://wordpress.org/plugins/json-api/screenshots/
I need to convert the PHP object to a JSON object somehow on the client side(the app which is not in Wordpress).
This bit here leaves me confused. You do not have PHP objects on the client-side, PHP is a back-end technology. What is returned to the client is a string which can be HTML, XML, JSON, plaintext on any other form of encoding.
That said, saying you have an object $obj in PHP, you could pass it to your front-end application creating an end-point retrieve_object.php and in there:
echo json_encode($obj);
So long as that is the only thing your are outputting, you lient-side app can make a request (Eg: AJAX) to retrieve_object.php and get the json object.
BUT , and this is important (!) in doing so you serialize object properties. You will lose any PHP object method. If any object property is an object itself (EG: A DB Connection) then this will be lost too.
Hope this helps!

parse foursquare json without 3rd party

Im using foursquare API in a web app, and I have the call to foursquare and the results dead on, but I can't parse it out in the way that I want. I don't want to use a 3rd party parser because those have confused me thoroughly. I want the app to alert out a list of clickable venue names, by distance, and when clicked a variable is assigned to the lat and lng of that venue.
$(document).ready(function(){
$.getJSON("https://api.foursquare.com/v2/venues/search?ll=-27.58818,-48.523248&
client_id=9&client_secret=9&v=20111107",
function(data){
//code here
});
});
The results look like this:
{"meta":
{"code":200},
"response":
{"venues":
[{"id":"4c158143a1010f47a1364e18",
"name":"Parma Pizza",
"contact":{"phone":"+554832346363","formattedPhone":"+55 48 3234-6363"},
"location":{"address":"R. Lauro Linhares, 1052",
"lat":-27.588341,
"lng":48.5232834,
"distance":18,
So far ive tried 3rd party Jackson with fail, alerting out names with fail, document.write with fail, and some type of .$each remover which also failed. Please help I am so stuck.
jQuery is already parsing your JSON file with $.getJSON. Unless you're using an old browser you don't need a 3rd party JSON parsing library. (Although you should include JSON3.js in your code base just in case someone trying to use your site is in an old browser. Just include it. You don't need to do anything else other than that.)
The data variable being passed into the callback function is a JavaScript object. You can then just do data.meta.code to get the value of code (200), or data.response[0].name to return Parma Pizza.
As for generating your list you're going to have to do the hard work. You can use $.each to iterate though the places easily though:
$.getJSON("https://api.foursquare.com/v2/venues/search?ll=-27.58818,-48.523248&client_id=9&client_secret=9&v=20111107", function(data){
$.each(data.response, function(index, elm){
console.log(elm.name);
});
});
Will print out a list of all the venue names returned from your query.
# Celeste
I think you can fix it by adding .venues in the code from tkone.
Atleast this worked for me.
$.getJSON("https://api.foursquare.com/v2/venues/search?ll=-27.58818,-48.523248&client_id=9&client_secret=9&v=20111107", function(data){
$.each(data.response.venues, function(index, elm){
console.log(elm.name);
});
Sorry for not commenting on tkone's answer, but I don't have reputation enough to comment :/ strange system ....

Categories

Resources