0

The JSON format I am getting is:

{
    "test":[
        {"key1":"value1"},
        {"key2":"value2"}
     ]
}

But is it possible to get this format instead?

{
    "test": {
        "key1":"value1",
        "key2":"value2"
    }
}

My php code is this:

$key=$row[1];
$value=$row[2];
$posts[] = array($key => $value);

$response['strings'] = $posts;
fwrite($out, json_Encode($response))

I've been stuck on this for hours, someone please help! Thanks in advance!

3 Answers 3

2

You want

$posts[$key] = $value;

The issue is that PHP arrays with string keys are objects in JSON terms.

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

Comments

1

the first one is an array, the 2nd is an object.

$posts = new stdClass();
$posts->key1 = "value1";
$posts->key2 = "value2";

$response['strings'] = $posts;
fwrite($out, json_Encode($response))

Comments

1

I assume your code looks like this:

$posts = array();
while( somthing )
{
  $row = ...

  $key=$row[1];
  $value=$row[2];
  $posts[] = array($key => $value);
}

$response['strings'] = $posts;
fwrite($out, json_Encode($response))

Your fix is to do this:

$posts = array();
while( somthing )
{
  $row = ...

  $key=$row[1];
  $value=$row[2];
  $posts[$key] = $value;
}

$response['strings'] = $posts;
fwrite($out, json_Encode($response))

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.