1

I've looked at how to decode a string here however it requires the key's be wrapped in quotes and my data doesnt, example:

The below data, is saved in a .txt file, I'm using file_get_contents() to read the files, I do not have control over the below data.

THIS IS MY DATA

"{
    ip : "192.168.1.110",
    startFrame : "1",
    endFrame : "11",
    startedCurrentFrameAt: "1397529891",
    status: "rendering",
    currentFrame: "0"
}"

In php, I want to be able to read this data, and access each key, this is what I've tried:

$arr = json_decode($data, true)['status'];

$arr just returns null, because the key's aren't quoted, is there a work around for this?

I've found many answers to this question, but all have the key's quoted.

5
  • Are you generating the JSON or are you getting it from somewhere ? Commented Apr 15, 2014 at 4:21
  • can you add json generated code also? Commented Apr 15, 2014 at 4:22
  • From 2.2. Objects An object structure is represented as a pair of curly brackets surrounding zero or more name/value pairs (or members). A name is a string. and from 2.5. Strings A string begins and ends with quotation marks. So those would technically be objects, which json does'nt support. the keys need to be strings my friend Commented Apr 15, 2014 at 4:24
  • @ShankarDamodaran I have edited my question, I'm basically reading a txt file which the data is automatically populated. Commented Apr 15, 2014 at 4:26
  • @AwladLiton I'm not generating the object, it's automatically pulled in through a .txt which I do not create/manage. Commented Apr 15, 2014 at 4:27

3 Answers 3

2

Try this

<?php
 function fix_json($s) {
  $s = preg_replace('/(\w+):/i', '"\1":', $s);
  return $s;
}


$data = '{
    ip: "192.168.1.110",
    startFrame: "1",
    endFrame: "11",
    startedCurrentFrameAt: "1397529891",
    status: "rendering",
    currentFrame: "0"
}';

$valid_json = fix_json($data);
$arr = json_decode($valid_json , true);
$status = $arr['status'];

echo $status;

DEMO

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

3 Comments

Please3 read my whole question, I do not have control over the quotes around the keys, unless I use a regex to add them.
My object is wrapped in "" not '', why does this matter? It doesn't seem to work unless it's single quotes not double
I eventually got this working, it wasn't work because I had spaces in my datakey : "s", I used another expression to remove the any spaces before a semi colon and it worked fine
1

Use preg_replace_callback() for this.


Well what is happening in the code ?

First, the regular expression is trying to find the entries between a space and a : , and then concatenates the quotes around them. Finally, an str_replace() acts a wrapper to fix the JSON braces.

<?php

$json='"{
    ip : "192.168.1.110",
    startFrame : "1",
    endFrame : "11",
    startedCurrentFrameAt: "1397529891",
    status: "rendering",
    currentFrame: "0"
}"';

function cb_quote($v)
{
    return '"'.trim($v[1]).'":';
}
$newJSON=str_replace(array('"{','}"'),array('[{','}]'),preg_replace_callback("~ (.*?):~","cb_quote", $json));
echo $arr = json_decode($newJSON, true)[0]['status'];

OUTPUT :

rendering

Working Demo

Through a file.. (Edit)

<?php
$json = trim(file_get_contents('new.txt'));
//Modifications..
$json = str_replace(array('{','}',':',','),array('[{" ',' }]','":',',"'),$json);
function cb_quote($v)
{
    return '"'.trim($v[1]).'"';
}
$newJSON=preg_replace_callback("~\"(.*?)\"~","cb_quote", $json);
echo $arr = json_decode($newJSON, true)[0]['status']; //"prints" rendering

8 Comments

I am still getting null with this, I can't define the $json variable like you have, to try and replicate, would I just write this $json = "'" . $data ."'"; ??
If you are getting that from a text file , simply do ... $json = trim(file_get_contents('yourjsonfile.txt'));
newJSON is defined, but if I just return $arr like so: return json_decode($newJSON, true); it is null...
Why in the world are you using return? Are you inside a function or what ?
I beleive it's formatting my string wrong, I've just seen in newJSON it's being formatted like so: "{ip"":""192.168.1.110",startFrame":""1",endFrame":""11",startedCurrentFrameAt":""1397529891",status":""rendering",currentFrame":""0"}"
|
0

I would do this by using the PHP explode function. Explode is like javascript's .split function, in that it will take a string and EXPLODE it into an array of usable data.

So, something like this should work, but you'll need to remove the "{ and }" on the ends first:

// lets assume that your data is $mydata, for brevity's sake.
$mydata_arr = new Array();
$item_arr = new Array();
$newdata_arr = new Array();

$mydata_arr = explode(',',$mydata); // explode where there is a comma

foreach($item in $mydata_arr){
    $item_arr = explode(':',$item); // explode where there is a colon
    // this gives us keys and values in a the $item_arr at [0] and [1]
    $key = $item_arr[0];
    $value = $item_arr[1]; 

    // reassign these in a new, usable array     
    $newdata_arr[$key] = $value;
}

Now, I know this is crude and inelegant, but I wanted to explain in a way that would help you see what needs to be done in something like English. I hope it helps.

2 Comments

I don't know where, but I believe there's an error somewhere, I can't get this to work :(
Have you removed the starting and ending bits? That would mess it up.

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.