網頁

顯示具有 JSON 標籤的文章。 顯示所有文章
顯示具有 JSON 標籤的文章。 顯示所有文章

2014年3月5日 星期三

Getting JSON out of Google Spreadsheets

檔案/發佈到網路/發佈工作表/取得公開資料連結/CSV   PHP轉JSON

 
Getting JSON out of Google Spreadsheets

header('Content-type: application/json');
 
// Set your CSV feed
$feed = 'https://docs.google.com/spreadsheet/pub?hl=en_US&hl=en_US&key=0Akse3y5kCOR8dEh6cWRYWDVlWmN0TEdfRkZ3dkkzdGc&single=true&gid=0&output=csv';
 
// Arrays we'll use later
$keys = array();
$newArray = array();
 
// Function to convert CSV into associative array
function csvToArray($file, $delimiter) { 
  if (($handle = fopen($file, 'r')) !== FALSE) { 
    $i = 0; 
    while (($lineArray = fgetcsv($handle, 4000, $delimiter, '"')) !== FALSE) { 
      for ($j = 0; $j < count($lineArray); $j++) { 
        $arr[$i][$j] = $lineArray[$j]; 
      } 
      $i++; 
    } 
    fclose($handle); 
  } 
  return $arr; 
} 
 
// Do it
$data = csvToArray($feed, ',');
 
// Set number of elements (minus 1 because we shift off the first row)
$count = count($data) - 1;
 
//Use first row for names  
$labels = array_shift($data);  
 
foreach ($labels as $label) {
  $keys[] = $label;
}
 
// Add Ids, just in case we want them later
$keys[] = 'id';
 
for ($i = 0; $i < $count; $i++) {
  $data[$i][] = $i;
}
 
// Bring it all together
for ($j = 0; $j < $count; $j++) {
  $d = array_combine($keys, $data[$j]);
  $newArray[$j] = $d;
}
 
// Print it out as JSON
echo json_encode($newArray);

2013年12月17日 星期二

js JSON

jQuery.getJSON and jQuery.parseJSON return [object Object]?

{"ocean":{"name":"North Atlantic Ocean"}}

  ,
 |

function initialize() {


        //http://api.geonames.org/oceanJSON?lat=40.78343&lng=-43.96625&username=demo
          var url = "http://api.geonames.org/oceanJSON";
          var move_add_center_lat = document.getElementById("add_center_lat").innerHTML ;
          var move_add_center_lng = document.getElementById("add_center_lng").innerHTML ;
          var username="XXXX";


          var getData = 'lat='+ move_add_center_lat+"&lng="+move_add_center_lng+"&username="+username; //'lat='+  '49.03' +"&lng="+'10.2';//
          var update_info;

              $.ajax({
               type: "Get",
               url: url,
               data: getData,
               success: function(data){
           
                          //{"ocean":{"name":"East China Sea"}}
                          var obj = $.parseJSON(JSON.stringify(data));
                          document.getElementById("info").innerHTML= obj.ocean.name;//JSON.stringify(jsonString);//json_data[0] ;
                },
                error: function(msg){


                    update_info = document.getElementById('info') ; //顯示點擊座標
                    update_info.innerHTML = "error";

                        
               }

            });

}

North Atlantic Ocean

jQuery AJAX POST Example


js將參數POST到PHP PHP將參數轉成JSON js ajax取得JSON

ajax-post.php
  if(isset($_POST['submit']))
  {
    echo "Data from server: ".json_encode($_POST)."
";
  }
  else
    echo "This is not a POST Request";

json.php


  
  



 
Click the button to display.
function myFunction()
{

      var formData = {name:"Ravi",loc:"India",age:31,submit:true};
      var url ="http://localhost/try/json/ajax-post.php";
          $.ajax(
              {
                  url : url,//"ajax-post.php",
                  type: "POST",
                  data : formData,
                  success: function(data, textStatus, jqXHR)
                  {
                    //data: data from server 
                      document.getElementById("demo").innerHTML= data ;
                       //alert('success');
                  },
                  error: function(jqXHR, textStatus, errorThrown)
                  {
                       for(var key in jqXHR) { //jqXHR = objects
                          var value = jqXHR[key];
                          document.getElementById("demo").innerHTML= jqXHR[key] ;
                      }
                  }
          }).done(function( html ) {
              //document.getElementById("demo").innerHTML= html ;
          });

}

Data from server: {"name":"Ravi","loc":"India","age":"31","submit":"true"}


解JSON





Click the button to display.
name=鼎泰豐,花園夜市,



 PHP取得JSON 傳值給JS處理

'\n' will break your JSON jQuery - WCF service call

特別注意字串要加單引號 json有了換行問題 要跳脫字元處理
 $pageContents = file_get_contents($url, false);
 $place_search_json_result = explode("debug/>",  $pageContents);
 $locations_db_json= $place_search_json_result[1];
 
    
 var jsonString = escapeNewLineChars('<?php echo $locations_db_json; ?>') ; // 注意字串單引
  var json_data = JSON.parse ( jsonString ); 


function escapeNewLineChars(valueToEscape) {
    if (valueToEscape != null && valueToEscape != "") {
        return valueToEscape.replace(/\n/g, "\\n");
    } else {
        return valueToEscape;
    }
}
jQuery JSON

jQuery.getJSON()

webGetJSON.php
error_reporting(E_ALL^E_NOTICE^E_WARNING); //關閉PHP的所有錯誤提示
 header("Content-type: application/json");
  $scenic_id = $_GET['scenic_id'];
  $radius = $_GET['radius'];
 
JSgetJSON.php
 
Click the button to display.
var ScenicAPI = "http://localhost/webGetScenic.php?jsoncallback=";

var jqxhr = $.getJSON( ScenicAPI,   
  {scenic_id: "2",radius: "300"})
  .done(function(json_data) {
   // console.log( "second success" );

     var getNames='name=';
    for (var i = 0; i < json_data.data.length; i++) {  

     getNames += json_data.data[i].name+',';

    }

    document.getElementById("demo").innerHTML= getNames ;
   
  })
  .fail(function() {
     console.log( "error" );
      alert("error");
  })

JSON.stringify 语法讲解

2013年10月31日 星期四

json google maps api v3


Google Geocoding API - JSON


Parse JSON data using jQuery.getJSON()


Now, we will primarily focus here on getting the values for the keys: formatted_address, lat andlng. Where,
  • formatted_address is a string containing the human-readable address of this location.
  • lat is the geocoded latitude value.
  • lng is the geocoded longitude value.
Now, we can get these values using jQuery like this:
1
2
3
4
5
6
7
8
9
10
11
12
var geocodingAPI = "http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true";
 
$.getJSON(geocodingAPI, function (json) {
    var address = json.results[0].formatted_address;
    console.log('Address : ', address);
 
    var latitude = json.results[0].geometry.location.lat;
    console.log('Latitude : ', latitude);
 
    var longitude = json.results[0].geometry.location.lng;
    console.log('Longitude : ', longitude);
});

2013年10月29日 星期二

JSON

json 2 html


你不可不知的 JSON 基本介紹

 

      var jsontext = '{"action": "success","data1": [{"lat": "25.0497226715","lng": "121.5073471069"}]}';
      var contact = JSON.parse(jsontext); 
      document.getElementById("lat").innerHTML= contact.data1[0].lat ;

2013年8月14日 星期三

php JSON

你不可不知的 JSON 基本介紹

error_reporting(E_ALL^E_NOTICE^E_WARNING); //關閉PHP的所有錯誤提示
header('Content-Type: application/json; charset=utf-8'); //記得加utf-8 解決亂碼

require_once("db.config.php");


$jsonString = '
 {
  'action':"ok",
  "contents":[
        {
            "Name": "涼宮ハルヒン",
            "Attrib": "SOS団長"
        },
        {
            "Name": "キョン",
            "Attrib": "普通人"
        }
  ], "data":{ "Name": "涼宮ハルヒン","Attrib": "SOS団長"}
}
';

$arr_json = json_decode( $jsonString );
echo $arr_json->data->Name . "
";
涼宮ハルヒン
$arr_json = json_decode( $jsonString );


  $json_output .= "debug/>";
  $json_output .= '{';
  $json_output .= '"action" :"success" ,';
  //傳送參數回傳 
  $json_output .= '"params" : ';
  $json_output .= $jsonString  ; 
  $json_output .= ', ';
  //傳送參數回傳 
  $json_output .= ' "data" : "';
   // echo  $arr_json->contents[1]->user_share_loc_id ;  
       foreach ($arr_json->contents as $key => $value) {
            echo $arr_json->contents[$key]->Name."\n";
            echo $arr_json->contents[$key]->Attrib."\n";
           $json_output_data .=  $arr_json->contents[$key]->Name.", ";

  $json_output .= $json_output_data;
  $json_output .= '"}';
  echo $json_output;   
涼宮ハルヒン
SOS団長
キョン
普通人
debug/>{"action" :"success" ,"params" : 
 {
  "contents":[
        {
            "Name": "涼宮ハルヒン",
            "Attrib": "SOS団長"
        },
        {
            "Name": "キョン",
            "Attrib": "普通人"
        }
  ]
}
,  "data" : "涼宮ハルヒン, キョン, "}
若為抓取頁面 切割過濾JSON外的方法
        $output = explode("debug/>",  $pageContents);
        $arr_json =json_decode($output[1]);
        $action = $arr_json->{'action'};
        echo  $action;
        echo  $arr_json->contents[0]->Name;
涼宮ハルヒン



Google Places API


https://maps.googleapis.com/maps/api/place/search/json?location=-33.8670522,151.1957362&radius=500&types=food&name=harbour&sensor=false&key=AddYourOwnKeyHere


{
    "debug_info": [],
    "html_attributions": [],
    "results": [
        {
            "geometry": {
                "location": {
                    "lat": 25.085571,
                    "lng": 121.564002
                }
            },
            "icon": "http://maps.gstatic.com/mapfiles/place_api/icons/cafe-71.png",
            "id": "3d7fbd4541ad66c611646f4f592fa12101a24170",
            "name": "肯達咖啡",
            "opening_hours": {
                "open_now": true
            },
            ...
]
       

        $url = "https://maps.googleapis.com/maps/api/place/search/json?location=25.091075,121.559834&sensor=false&radius=700&types=cafe&key=yourkey";
      $place_search_json_result = file_get_contents($url, false);
       $jsonContent =json_decode($place_search_json_result);

       echo  $jsonContent->results[0]->name ;

       $geo_result =  $jsonContent->results[0];
       echo  '(' ;
       echo  $geo_result->geometry->location->lat;
       echo  ',' ;
       echo  $geo_result->geometry->location->lng;
       echo  ')' ;
肯達咖啡(25.085571,121.564002) php取得json
       

    $pageContents = file_get_contents($url, false);
  $place_search_json_result = explode("debug/>",  $pageContents);
  $locations_db_json =$place_search_json_result[1];
php傳值json給js
  

          // var locations = [
      //       {
      //           latlng : new google.maps.LatLng(25.0336148,  120.56480220000003),
      //                 info : "hello"
            
      //       },
      //       {
      //           latlng : new google.maps.LatLng(25.0336148,  121.56480220000003),
      //             info : "world"
      //       }

      //   ];
     var locations = [
                    
           ];

          for (var i = 0; i < locations.length; i++) {  
          var marker = new google.maps.Marker({
              position: locations[i].latlng,
            //icon: pinkmarker,
            //shadow: shadow,
            map: map
          });



          google.maps.event.addListener(marker, 'click', (function(marker, i) {
            return function() {

              infowindow.setContent(locations[i].info);
              infowindow.open(map, marker);
            }
          })(marker, i));
        }     
google spreadsheets return json
 
header('Content-type: application/json; charset="utf-8"');

$google_sheet_api = 'https://spreadsheets.google.com/feeds/list/1IKeEX6Vbn-T8pCiwLqURgYf_GGojE198iXXIS93_bD4/od6/public/values?alt=json';

 $api_json = file_get_contents($google_sheet_api);

 $api_json_str_replace = str_replace("$","",$api_json);

 $arr_json = json_decode(stripslashes($api_json_str_replace));
 //echo  $arr_json->version;
 //echo  $arr_json->feed->xmlns;
 //echo  $arr_json->feed->title->type;
 //echo  $arr_json->feed->title->t; //工作表1
 //echo  $arr_json->feed->entry[0]->gsxname->t;
 //echo  $arr_json->feed->entry[0]->gsxlatitude->t.",";
 //echo  $arr_json->feed->entry[0]->gsxlongitude->t;

 
 $data =[];

       foreach ($arr_json->feed->entry as $key => $value) {

         $name = $arr_json->feed->entry[$key]->gsxname->t;
         $latitude = $arr_json->feed->entry[$key]->gsxlatitude->t;
         $longitude = $arr_json->feed->entry[$key]->gsxlongitude->t;
         $address = $arr_json->feed->entry[$key]->gsxaddress->t;
 

         $record_array_preson = array("id"=>$key,"name"=>$name,"latitude"=>$latitude,"longitude"=>$longitude,"address"=>$address); 
         array_push($data,  $record_array_preson);

      }
       $json_output .= json_encode($data) ;

   echo $json_output; 
[
  {
    "id": 0,
    "name": "家樂福重慶店",
    "latitude": "25.0591477",
    "longitude": "121.5138074",
    "address": "台北市大同區重慶北路二段171號"
  },
  {
    "id": 1,
    "name": "家樂福大直店",
    "latitude": "25.0824879",
    "longitude": "121.5580935",
    "address": "台北市中山區樂群三路218號"
  },
..
]

2012年7月12日 星期四

jSON NSUserDefaults

讀JSON 更新資料 存進NSUserDefaults


 JSON

 { "Content": [{"p1":"-1","p2":"-1","p3":"-1","p4":"-1","p5":"-1"}] }
 
{
    NSDictionary *jSON;
    NSArray *tests;
}

@property (nonatomic,strong) NSDictionary *jSON;
@property (nonatomic, strong) NSArray *tests;
 
@synthesize jSON,tests;

- (void)viewDidLoad
{
    [super viewDidLoad];
 // Do any additional setup after loading the view, typically from a nib.
    
    
    //JSON
    NSString *testJSON = [[NSString alloc] initWithFormat: @"1_result_1"];
    
    jSON = [self initParseJSONData:testJSON];
    self.tests  = [jSON objectForKey:@"Content"]; 
    NSLog(@"JSON self.tests=%@",self.tests );
    
    //update rrowData
    NSObject *rowData = [self.tests  objectAtIndex:0];
    [rowData setValue:@"1" forKey:@"p3"];
    NSLog(@"Update rowData=%@",rowData );
    
    //NSUserDefaults
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    
    [def setObject:rowData forKey:@"savedPArray"];
    
    NSMutableArray *mutableArray= [def objectForKey:@"savedPArray"] ;
    NSLog(@"NSUserDefaults Get=%@",mutableArray);
    
    NSString *getP3= [[def objectForKey:@"savedPArray"] valueForKey:@"p3"];
    NSLog(@"NSUserDefaults Get=%@",getP3);
    

}

- (NSDictionary*)initParseJSONData:(NSString *)fileName
{
    
    NSString *unitJSON = [[NSString alloc] initWithFormat:fileName];
    
    //parseJSONData
    
    NSString *jsonPath = [[NSBundle mainBundle] pathForResource:unitJSON ofType:@"txt"];
    NSData *data = [NSData dataWithContentsOfFile:jsonPath];
    
    NSString *jsonReturn =  [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    
    SBJsonParser *parser = [[SBJsonParser alloc] init];
    

    NSDictionary *jSON = [parser objectWithString:jsonReturn error:nil];  
    
    return jSON;
    
}

結果



2012-07-13 11:33:15.425 NSUserDefaultsHSK[2060:f803] JSON self.tests=(
        {
        p1 = "-1";
        p2 = "-1";
        p3 = "-1";
        p4 = "-1";
        p5 = "-1";
    }
)
2012-07-13 11:33:15.452 NSUserDefaultsHSK[2060:f803] Update rowData={
    p1 = "-1";
    p2 = "-1";
    p3 = 1;
    p4 = "-1";
    p5 = "-1";
}
2012-07-13 11:33:15.459 NSUserDefaultsHSK[2060:f803] NSUserDefaults Get={
    p1 = "-1";
    p2 = "-1";
    p3 = 1;
    p4 = "-1";
    p5 = "-1";
}
2012-07-13 11:33:15.460 NSUserDefaultsHSK[2060:f803] NSUserDefaults Get=1

2012年5月16日 星期三

Xcode test JSON

  
  "test": [
    {
      "question": {
        "name": "A",
        "chinese": "這是JSON問句測試?"
      },
      "answer": {
        "name": "B",
        "selection": [
          {
            "chinese": "這是JSON答案測試選項A。"
          },
          {
            "chinese": "這是JSON答案測試選項B。",
            "answer": "YES"
          }
        ]
      }
    }
   ]
  
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    // Return the number of sections.
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    int rowCount =0;
    
    switch (section) {
        case 0:
            rowCount = 1; //問句
            break;
        case 1:
            rowCount = [[[[self.tests objectAtIndex: 0] objectForKey: @"answer"] objectForKey: @"selection"] count]; //答案選項
            break;
        default:
            break;
    }
    
    return rowCount;
}
  
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"CellIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    
    // Configure the cell...
    

    if (indexPath.section==0) {
        
        NSDictionary *each = [self.tests objectAtIndex:0];
        
        NSString *text = [[NSString alloc] initWithFormat: @"Q: %@", 
                          [[each objectForKey: @"question"] objectForKey: @"chinese"]];
        cell.textLabel.text = text;
    }
    else {
        
        
        NSDictionary *eachJSON = [[[[self.tests objectAtIndex: 0] 
                                    objectForKey: @"answer"] 
                                   objectForKey: @"selection"] 
                                  objectAtIndex: indexPath.row];
        
        NSLog(@" eachJSON selection  : %@", eachJSON ); 
        
        NSLog(@" eachTKB  chinese: %@",[eachJSON objectForKey: @"chinese"]);
        
        cell.textLabel.text = [eachJSON objectForKey: @"chinese"];
    }
          
    
    return cell;
}
  
2012-05-17 10:46:04.346 multiNodeJSON[1733:f803]  eachJSON selection  : {
    chinese = "\U9019\U662fJSON\U7b54\U6848\U6e2c\U8a66\Uff21\U3002";
}
2012-05-17 10:46:04.347 multiNodeJSON[1733:f803]  eachTKB  chinese: 這是JSON答案測試A。

2012年5月3日 星期四

json-framework xcode

Download json-framework


{ "jsonNode": [ {"ID":"1","name":"A"}, {"ID":"2","name":"B"}] }
#import "SBJson.h"


 

#import "ViewController.h"
#import "SBJson.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self initParseJSONData];

}

- (void)initParseJSONData
{
    //parseJSONData
    
    NSString *jsonPath = [[NSBundle mainBundle] pathForResource:@"jsonfile" ofType:@"txt"];
    NSData *data = [NSData dataWithContentsOfFile:jsonPath];
    
    NSString *jsonReturn =  [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    
    SBJsonParser *parser = [[SBJsonParser alloc] init];
    
    
    NSDictionary *jSON = [parser objectWithString:jsonReturn error:nil];  
    
    NSMutableArray * jsonData =  [jSON objectForKey:@"jsonNode"]; 
    NSLog(@"jsonFindData %@",jsonData);
    
    CellItem = [jsonData valueForKey:@"name"]  ;
    NSLog(@"jsonFindItem: %@",CellItem);
}


readJSON[4392:f803] jsonFindItem: (
    A,
    B
)
與Table結合 .h
 
#import 


@interface jsonTableView : UITableViewController
{
    NSArray *CellItem ;
}

.m
 
#import "SBJson.h"

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    // Return the number of rows in the section.
    return [CellItem count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Celldata";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    // Configure the cell...
    cell.textLabel.text = [CellItem objectAtIndex:indexPath.row];
    
    return cell;
}



Cell 上為Label的版本
 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Celldata";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    // Configure the cell...
   // cell.textLabel.text = [CellItem objectAtIndex:indexPath.row];
    
    NSString *text = [CellItem objectAtIndex:indexPath.row];
   // NSString *textLong = [[NSString alloc] initWithFormat: @"%@: %@",[CellItemID objectAtIndex:indexPath.row], [CellItem objectAtIndex:indexPath.row]];
    
    UILabel *cellLabel = (UILabel *) [cell viewWithTag:2] ; //Label設Tag 2
    
    cellLabel.lineBreakMode = UILineBreakModeWordWrap; //設置換行
    cellLabel.numberOfLines = 0; //設置自動行數
    [cellLabel setText:text];

    
    return cell;
}
最外層非NSDictionary格式
[ {"ID":"1","name":"A"}, {"ID":"2","name":"B"} ]
- (void)viewDidLoad
{
    [super viewDidLoad];

    [self initParseJSONData];

}

- (void)initParseJSONData
{
    //parseJSONData
    
    NSString *jsonPath = [[NSBundle mainBundle] pathForResource:@"jsonfile" ofType:@"txt"];
    NSData *data = [NSData dataWithContentsOfFile:jsonPath];
    
    NSString *jsonReturn =  [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    
    SBJsonParser *parser = [[SBJsonParser alloc] init];
    
    
    NSMutableArray *jSON = [parser objectWithString:jsonReturn error:nil];
    CellItem = jSON  ;
    NSLog(@"jsonContent: %@",jSON);
    
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Celldata";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    // Configure the cell...
   // cell.textLabel.text = [CellItem objectAtIndex:indexPath.row];
 
    
    NSDictionary *jsonData = [CellItem objectAtIndex: indexPath.row];
    UILabel *cellLabel = (UILabel *) [cell viewWithTag:2] ;
    
    cellLabel.lineBreakMode = UILineBreakModeWordWrap; //設置換行
    cellLabel.numberOfLines = 0; //設置自動行數
    [cellLabel setText:[jsonData objectForKey: @"name"]];

    
    return cell;
}