0

Here is my Json. This ia an dwr response ( a webservice created in java) .

{
  key1 : {
     date : "Today" ,
     items : [
           {
             itemKey1 : "itemValue1",
             itemKey2 : "itemValue2",
           },
             {
             itemKey1 : "itemValue1",
             itemKey2 : "itemValue2",
           },
     ]
   }
}

JSON LINT is also showing the error.

If you can see key do not have "" may be that's why i can not parse it to json in php directly. Is there any way oi can parse it to json and then to array or directly to an array.

But when i transfor this to this type of json it. In JSON LINT it shows that it is proper json.

{
"key1": {
    "date": "Today",
    "items": [
        {
            "itemKey1": "itemValue1",
            "itemKey2": "itemValue2"
        },
        {
            "itemKey1": "itemValue1",
            "itemKey2": "itemValue2"
        }
    ]
 }
}

So is there anyway i can trasnfer json to second type. Dynamically in PHP

10
  • @Gerton via JSON LINT i get => Parse error on line 1: { key1: { date -----^ Expecting 'STRING', '}' Commented May 12, 2015 at 9:06
  • @Uchiha It is not working ...!!! It returns nothing,.... Commented May 12, 2015 at 9:08
  • This is not valid JSON... JSON needs to have key names wrapped in quotes. Commented May 12, 2015 at 9:12
  • Yeah that is my problem... Is there any way i can dynamically assign quotes to the keys ???? @EJTH Commented May 12, 2015 at 9:14
  • Is there any reason you couldn't just serialize the data properly? Are you or your organization responsible for the java service? If so you should really change that to be JSON compliant instead of doing wierd wrangling of the data. But i suppose you COULD do some ugly regex to compensate for the missing quotes, but it WILL be flaky! Commented May 12, 2015 at 9:15

1 Answer 1

1

Since there is no javascript parser build in to PHP and what you have here is JAVASCRIPT and not JSON, your only options is really to implement your own parser / use an existing parser. OR wrangle your string into being JSON, this COULD be done with something like regex, though it will most likely be flaky.

For your specified example data, this would do:

<?php
$data = json_decode(preg_replace_callback('#(\S+)\s*:#i', function($matches){
  return '"'.$matches[1].'" :';
},$str));
Sign up to request clarification or add additional context in comments.

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.