简体   繁体   中英

Working with line delimited JSON strings in PHP

I am using an API which requires I send it data as new line delimited JSON, for example;

{"id":"67523", "name":"Jason"}
{"id":"69928", "name":"Doug"}

The API accepts single JSON objects, but can accept multiple new line delimited JSON objects in a single batch (more efficient). How do you construct string objects like the above in PHP?

If taking a string like {"id":"67523", "name":"Jason"} , I can json_decode() it to turn it into an associative array (this is accepted by the API endpoint). However, the only way I can see to pass a number of these objects together is within an array, but the API does not accept an array of JSON objects.

If API really accepts newline delimited objects, and manage objects over json level, try:

$data = '{"id":"67523", "name":"Jason"}'."\r\n".'{"id":"69928", "name":"Doug"}';

In php also you can use new lines just inside string code.

You would want to json_encode each individual object/array. However, you can do this in such a way that you don't have to concat each individual object.

$a = ['id' => 67523, 'name' => 'Jason'];
$b = ['id' => 69928, 'name' => 'Doug'];

echo implode("\r\n", array_map('json_encode', [$a, $b]))

Output:

{"id":67523,"name":"Jason"}\r\n
{"id":69928,"name":"Doug"}

JSON does not allow real line-breaks.
As you said API is accepting Single Objects and not accepting an array of JSON objects, the below Code will help you somewhat where each object is given index

{
  0: {
    "id": "67523",
    "name": "Jason"
  },
  1: {
    "id": "69928",
    "name": "Doug"
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM