0

Im using google api for generating places and maps. I have the json parsing code in php and i need it in javascript can someone help me with my code

<?php
$json_string = file_get_contents("https://maps.googleapis.com/maps/api/place/textsearch/json?query=pizza&sensor=false&key=MYKEY");
  $parsed_json = json_decode($json_string);

  $var = $parsed_json->{'results'}[0]->{'formatted_address'};
?>

so with [0] im referring to the first result, how can do it in javascript ?

2 Answers 2

1

JavaScript supports JSON by default, there is no need to encode it.

$json = '{ "some": "valid", "json": "string" }';
$js = "var json_data = " . $json . ";";
echo $js;

This will print:

var json_data = { "some": "valid", "json": "string" };

If you don't have a JSON string - but a PHP array - you would use json_encode. Like so:

$json = '{ "some": "valid", "json": "string" }';
$json_data = json_decode($json); // now we have the JSON available in PHP mem
$js = "var json_data = " . json_encode($json_data) . ";";
echo $js;
Sign up to request clarification or add additional context in comments.

6 Comments

Maybe you did not understand my question. I need the code in javascript to access json data in javascript.
JSON data from PHP right? Then PHP can print a script fragment to import the data to JavaScript (which is what my code does).
What i want to do is parse external json data like the one i mentioned from googleapi in javascript not in php. To read the json specific row for ex [0] but in javascript. I dont know if this is understandable. Thank you
Show us how you are calling this API in JavaScript then. I assume Google just has a whole library for you to use and you don't need to worry about JSON, you just get the data in JavaScript memory.
<script src="ajax.googleapis.com/ajax/libs/jquery/1.5.1/…> <script> jQuery(document).ready(function($) { $.ajax({ url : "api.wunderground.com/api/a979d8540526825e/geolookup/conditions/…", dataType : "jsonp", success : function(parsed_json) { var location = parsed_json['location']['city']; var temp_f = parsed_json['current_observation']['temp_f']; alert("Current temperature in " + location + " is: " + temp_f); } }); }); </script> Here for example how can i alert specific row for example ['location'][0] this is not workin
|
0

All latest browsers supports parsing json natively. Usibg JSON.parse and JSON.stringify methods. For others use jquery builtin functions

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.