假设我将JSON存储在MySQL中作为JSON类型:
{"key1":"value1","key3":"value3","key2":"value2"}
我要插入" key4":" value4"在特定的位置,例如:
{"key1":"value1", "key4":"value4" ,"key3":"value3","key2":"value2"}
是否有纯粹的MySQL命令来执行此操作?
JSON_INSERT看起来只能附加到JSON。
我宁愿把它作为一个MySQL命令来保持它的效率,否则,我将不得不拉出整个JSON字符串,解码它,做一些PHP命令,然后恢复它。似乎应该有一种MySQL的说法,把它放在索引2左右。
任何指导都将不胜感激。
答案 0 :(得分:0)
我建议您使用JSON数组进行序列化。这是一个例子:
var a = [{key1: "va1"},{key1: "val2"}];
然后,您将使用splice()来推送JSON数组中的特定索引。 Splice()是一个javascript函数。
a.splice(1, 0, {key1: 'adipiscing'});
尝试在下面运行我的代码段:(顺便说一句,我使用的是AngularJs)
<div ng-app="myApp" ng-controller="myCtrl">
{{text}}
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
var a = [{key1: "jp"},{key1: "id"}]
a.splice(1, 0, {key1: 'adipiscing'})
$scope.text = a;
});
</script>
&#13;
答案 1 :(得分:0)
正如@Sloan指出你可以使用JSON特定的函数,或者你可以使用几个SQL hacks来完成这个。
方法1:
您可以像这样更新字段。这会将新值附加到字段的末尾。
UPDATE tablename SET fieldname=INSERT(fieldname, length(fieldname), 0, ',"key4":"value4"') WHERE .....
在PHP中,它看起来像这样。此方法的缺点是该值被追加并且未插入到特定位置。其次,它只能添加到现有数据中。
$indata = '"key4":"value4"';
$SQL = "UPDATE tablename SET fieldname=INSERT(fieldname, length(fieldname), 0, ',$indata') WHERE .....";
方法2:
如果有多个项目,此查询会在第二个位置(根据您的要求)插入新项目,否则将像上一个查询一样附加它
UPDATE tablename SET fieldname=INSERT(fieldname,IF(LOCATE(',',fieldname)>0, LOCATE(',',fieldname) , length(fieldname)), 0, ',"key4":"value4"') WHERE ...;
在PHP中
$indata = '"key4":"value4"';
$SQL = "UPDATE tablename SET fieldname=INSERT(fieldname,IF(LOCATE(',',fieldname)>0, LOCATE(',',fieldname) , length(fieldname)), 0, ',$indata') WHERE ...;";
<强>更新强>
// JSON Object
{"key1":"value1","key3":"value3","key2":"value2"}
// Object properties do not have order so you can only add new properties
// JSON Array (of objects)
[{"key1":"value1"},{"key3":"value3"},{"key2":"value2"}]
// With array you can have order. So you can use 'JSON_ARRAY_INSERT()'
// To Add to position 2
// eg: UPDATE tablename SET fieldname=JSON_ARRAY_INSERT(fieldname, '$[1]', '{"key4":"value4"}');
注意:我还没有对此进行测试,因此您可能需要对其进行调整。
答案 2 :(得分:0)
// Watch out, this test is written with the latest ember-qunit syntax which might not be exactly what you have in your Ember 2.16 application
import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render } from 'ember-test-helpers';
import hbs from 'htmlbars-inline-precompile';
module('your component integration tests', function(hooks) {
setupRenderingTest(hooks);
test('clicking the OK confirm button', async function(assert) {
// save the original window.confirm implementation
const originalWindowConfirm = window.confirm;
// simulate the OK button clicked
window.confirm = function() { return true;}
// ADD YOUR TEST AND ASSERTIONS HERE
// restore the original window.confirm implementation
window.confirm = originalWindowConfirm;
});
});