0

I have a json file which I need to update its numerical values and write back to new file.This is the sample script I have

[
  {
    "type": "flipImage",
     "image": "img/new.jpg",
     "trigger": "{{10,80},{300,350}}",
     "animationDuration": "1.0"
   }
 ]

The numerical values of "trigger": "{{10,80},{300,350}}" need to update to some other value. I am managed to get the value by json_decode() in php . After decoding it is returning the value {{10,80},{300,350}}

This is script for decoding

$json_data  = file_get_contents('json.txt');    
$encoded_data = json_decode($json_data,true);   
echo $encoded_data[0]['trigger'];

But I got stuck in the updating part . How can I split the value, then update and write back the updated json file?

Any help highly appreciable.

Update First I need parse that numerical values then I have some calculations on it. After calculation write back the entire json to new file

2
  • You don't need to parse {{10,80},{300,350}} if you just want to overwrite it, do you? Commented Aug 13, 2013 at 9:54
  • @ÁlvaroG.Vicario First I need parse that value then I have some calculations on it. After calculation write back the entire json to new file Commented Aug 13, 2013 at 9:57

3 Answers 3

1

If you're kind of sure that you won't find variations on the format, it's quite a simple regular expression (escaping makes it look harder than it is):

<?php

$input = '{{10,80},{300,350}}';
$output = null;

if( preg_match('/^\{\{(\d+),(\d+)\},\{(\d+),(\d+)\}\}$/', $input, $matches) ){
    // Example: increment all numbers in 1
    $matches[1]++;
    $matches[2]++;
    $matches[3]++;
    $matches[4]++;

    $output = sprintf('{{%d,%d},{%d,%d}}', $matches[1], $matches[2], $matches[3], $matches[4]);
}

var_dump($output);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your great answer. It works for me. I need to look into the regular expressions.
1

With file updating:

<?php
$file = 'json.txt';
$json_data = file_get_contents($file);    
$encoded_data = json_decode($json_data,true);  

$encoded_data[0]['trigger'] = "{{X,Y},{X,Y}}"; // New value

// Update file
$fp = fopen($file, 'w+');
fputs($fp, json_encode($encoded_data));
fclose($fp);
?>

Comments

0

Try this

If the values are fixed(4) only then create 4 variables like

$tr=$encoded_data[0]['trigger'];
$x1=$tr[0][0];
$y1=$tr[0][1];
$x2=$tr[1][0];
$y2=$tr[1][1];
// do calculations here
$encoded_data[0]['trigger']="{{$x1,$y1},{$x2,$y2}}";
echo json_encode($encoded_data);

2 Comments

thanks for replying @Rohan Kumar . But first i need to parse the value and then do some calculations. That value i need to write into the php file
Please note that trigger does not contain JSON.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.