“解析JSON字段值时出错。在[16]处发生意外的OBJECT_START,field = add”,通过cURL

时间:2018-07-17 17:39:25

标签: php json curl solr

基于示例here(以及其他地方),我试图将记录添加到简单的Solr索引(仅有的字段为srcdest,它们都是单个值字符串字段,并将solrconfig设置为使用以下代码通过PHP和cURL自动生成id值:

$data = array(
  "add" => array(
    "doc" => array(
      "src" => $src,
      "dest" => $dest
    ),
    "commitWithin" => 1000,
  ),
);

$data_string = json_encode(array($data));
$add_url = 'https://my-solr-url.com/solr/my_index/update?commit=true&wt=json';
$add_ch = curl_init($add_url);
curl_setopt($add_ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($add_ch, CURLOPT_POST, 1);
curl_setopt($add_ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
curl_setopt($add_ch, CURLOPT_POSTFIELDS, $data_string);
$add_response = json_decode(curl_exec($add_ch));
curl_close($add_ch);

但是,当我运行它时,出现以下错误:

Error parsing JSON field value. Unexpected OBJECT_START at [16], field=add

基于Solr docs,我尝试了以下变体:

$data = array(
  'src' => $src,
  'dest' => $dest
);

$data_string = json_encode(array($data));
$add_url = 'https://my-solr-url.com/solr/my_index/update/json/docs?commit=true&wt=json';
$add_ch = curl_init($add_url);
curl_setopt($add_ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($add_ch, CURLOPT_POST, 1);
curl_setopt($add_ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
curl_setopt($add_ch, CURLOPT_POSTFIELDS, $data_string);
$add_response = json_decode(curl_exec($add_ch));
curl_close($add_ch);

但是现在我收到关于Unknown field src的错误。从我所看到的,我遵循文档,但没有任何效果。我需要更改什么?

1 个答案:

答案 0 :(得分:0)

所以事实证明问题出在我正在创建一个双精度数组:

$data = array(
  "add" => array(
    "doc" => array(
      "src" => $src,
      "dest" => $dest
    ),
    "commitWithin" => 1000,
  ),
);

$data_string = json_encode(array($data));

我将最后一行更改为

$data_string = json_encode($data);

工作正常。