0

I'm building a JSON with PHP, and the keys can't be quoted, because I need to import it into Neo4j.

I'm using this to build it in PHP, inside a loop:

$contacts[$contact_key]["addr"][$addr_key]["zipcode"] = $zip_match[0];
$contacts[$contact_key]["addr"][$addr_key]["housenumber"] = $house_match[0];

And eventualy I use:

$reencoded = json_encode($contacts, JSON_UNESCAPED_UNICODE);        
$reencoded = preg_replace('/"([^"]+)"\s*:\s*/', '$1:', $reencoded);

So this is a part of the JSON string result:

{addr:{1:{zipcode:"1315 GN",housenumber:"1229P;"}}

But I can't have numbered keys like 1:, 2: ect. because that gives me a error in Neo4j.

I preferly need to achieve this format:

{addr: [{zipcode:"1315 GN",housenumber:"1229P"}]

How can I make a list of adresses for a contact person, without having numbered keys?

1
  • 3
    I think if you start $contact_key at 0 and increment it then the numbers will be absent in the JSON. But the non-quoted keys is NOT valid JSON so what is Neo4j doing? Commented Sep 14, 2016 at 17:49

1 Answer 1

2

Instead of trying to remove the numeric keys you're getting from $addr_key from your JSON, just don't include them to begin with.

For the code inside your loop, you can add the addresses with [] instead, like this:

$address = ['zipcode' => $zip_match[0], 'housenumber' => $house_match[0]];
$contacts[$contact_key]["addr"][] = $address;
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks code looks cleaner now, but I still get the numbers. Isn't it because $contacts[$contact_key]["addr"] is already filled/not empty?
When you add the addresses using [], PHP will automatically create zero-based integer indexes for the addr array. When you json_encode an array like that, you should end up with a JSON array ([]) rather than a JSON object ({}). The keys should not be showing up in the JSON.
I now use: $contacts[$contact_key]["addrs"][] to have a zero-based integer index, and at the start of the loop I do: unset($contacts[$contact_key]["addr"]); I now have a empty addr: [] present in the JSON result. But I think I can be happy right now.

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.