3

Apache SOLR calls for a quirky JSON format when you want to add multiple entries at once. ( http://wiki.apache.org/solr/UpdateJSON#Update_Commands -- notice the 'add' nodes)

In a nutshell, I need to be able to create JSON that looks like this:

{
   "key": "val 1",
   "key": "val 2"
}

In PHP, you can easily create an array, but this JSON structure calls for an object with two keys of identical name that are explicitly not in an array.

0

2 Answers 2

2

While json_encode can't do that directly, you can work around it. Try this:

$php_friendly_json = json_encode([
 "key1" => "val 1",
 "key2" => "val 2"
]);

$apache_weird_json = str_replace(["key1", "key2"], "key", $php_friendly_json);

Of course, be sure to pick key1 and key2 such that they aren't going to be in the values of your JSON!

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

Comments

1

You aren't going to be able to do this using json_encode because it's not valid JSON. (Keyspace collision)

You are going to need to assemble the object manually.

You might consider creating the individual items, then using implode(). Then you can prepend and append { and }.

This would actually feel cleaner to me then hacking away at PHP to get json encoding to work.

Suggested Alternative

I'm a big fan of the Solarium Project for PHP and Solr.

Bulk Adds and pretty easy take a look here: http://wiki.solarium-project.org/index.php/V2:BufferedAdd_plugin

4 Comments

why do you claim it's not valid? JSON is defined mostly in terms of its syntax, the relevant RFC does say that names in objects "should" be unique, but "should" only means: "there may exist valid reasons in particular circumstances to ignore a particular item".
Okay, yeah, it's valid JSON, but as I mentioned in my answer, the key collissions make it impossible to form using json_encode. And as you would expect, you can't decode it either. codepad.org/hpJk8OSK It's perfectly valid, but totally wrong JSON.
Would you judge the validity of XML by how well it maps to SimpleXML?... or call it "wrong" when it doesn't?
That's oranges and apples. Everyone who usines simplexml knows the quirks of loading XML. Plus XML doesn't have the same key restrictions as JSON. I'm not arguing with you, you were right, that is perfectly valid JSON that he pasted, but it's also totally wrong.

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.