0

Is it possible to pass JSON in a URL?

For example, I have an array:

data = {  
  "name": "test",
  "user_id": 1
}

I want to pass it in to a URL like:

http://example.com/jsonArray
6
  • data is not an array in your case, it's a JSON object. Why not using POST method to send your data object ? Commented May 31, 2018 at 11:57
  • 3
    Yeah you can but why on earth would you want this? This is what POST requests are for :) Commented May 31, 2018 at 11:57
  • can't use post method as have to make a specific url to call api. Commented May 31, 2018 at 12:00
  • Maybe take a look at graphql api which seems more adapted than rest for what you want to do Commented May 31, 2018 at 12:01
  • worked with post requests and its working, but our task was to make a specific url to call an api. Commented May 31, 2018 at 12:01

2 Answers 2

2

You should better use POST to pass such type of data, but, absolutely you could make a :

$str = serialize(json_decode($data, true));

And then pass you $str in url.

Sign up to request clarification or add additional context in comments.

Comments

0

You can't send the JSON array directly, but you can prepare it in a way that allows it to be sent to your API. You turn your JSON into a string and encode it so it will be properly formatted for a GET.

// your JSON data
var data = '{"name":"Homer Simpson","status":"Suspended","disciplinary-dates":["2018-01-2","2018-02-14","2018-03-17"]}' ;

// take your JSON, turn it into a string and then encode it 
var urlParams = encodeURIComponent(JSON.stringify(data)) ;

// your URL adding your JSON data as the value
var url = 'http://example.com/?params=' + urlParams ;

On the PHP side you will decode

  // note: this code does not have any error checking - you should add it      
  // get your params
  $params = $_GET['params'] ;

  // decode the string
  $decodedParams = urldecode($params) ;

  // turn your string into an array
  $wasJSONAsArray = json_decode($decodedParams, true) ;

  // turn your string into a std object
  $wasJSONAsStdObj = json_decode($decodedParams) ;

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.